-1
{
  _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

Mhd
  • 817
  • 1
  • 8
  • 21
  • Does this answer your question? [Find in Double Nested Array MongoDB](https://stackoverflow.com/questions/29071748/find-in-double-nested-array-mongodb) – xdeepakv Jan 14 '22 at 17:18

1 Answers1

0

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/

Saurabh Lende
  • 953
  • 2
  • 13
  • 19