Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding a nested object in an array of object using mongoose

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading