{
_id: new ObjectId("61da0ab855483312e8f4483b"),
products: [
{
createdAt: 2022-01-08T22:05:44.635Z,
_id: new ObjectId("61da0ab855483312e8f4483c"),
productCode: 'otf',
productName: 'facebookmeta',
claims: [Array],
permissions: []
},
{
createdAt: 2022-01-08T22:05:44.635Z,
_id: new ObjectId("61da0ab855483312e8f4483f"),
productCode: '4pf',
productName: 'twitteroauth',
claims: [Array],
permissions: [Array]
}
],
__v: 0
}
Now i’ve been trying to get just one object from this array with the find() and findOne method without any luck. if i pass in a certain conditions, it still ends up giving me back an array with both objects. i just want to be able to dynamically pass conditions that belongs to a single object in the array and retrieve that object
>Solution :
MongoDB is applying query conditions on collection and returns the result with the matching documents. As both products twitteroauth & facebookmeta are part of the same document so the whole matching document will be returned.
If you want only a single matching entry in the document then you can use the MongoDB aggregation pipeline (with $unwind) where you can modify the result set.
For example:
db.collection_name.aggregate([
{
"$match": {
// pass matching criteria/conditions here
}
},
{
"$unwind": "$products" //to deconstruct products field in the result
},
{
"$match": {
"products.productName": "twitteroauth"
}
}
])
Note that the second match condition is used to add additional matching criteria/conditions on the deconstructed result set so that products can be filtered.
This will get you the result something like this:-
{
_id: new ObjectId("61da0ab855483312e8f4483b"),
products: {
createdAt: 2022-01-08T22:05:44.635Z,
_id: new ObjectId("61da0ab855483312e8f4483f"),
productCode: '4pf',
productName: 'twitteroauth',
claims: [Array],
permissions: [Array]
},
__v: 0
}
Reference: https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/