Home > Blockchain >  Find by key for nested object in mongoose
Find by key for nested object in mongoose

Time:06-08

I want to find a document based on key for nested object in mongoose. For example

{
     "_id": 1,
     "first_name": "Tom",
     "email": "[email protected]",
     "ACL": {
        123gd: {
          read: true,
          write: false,
        },
        3sg2w: {
          read: true,
          write: false,
        }
     }
},
{
     "_id": 2,
     "first_name": "Tom",
     "email": "[email protected]",
     "ACL": {
        546er: {
          read: true,
          write: false,
        },
        98trw: {
          read: true,
          write: false,
        }
     }
}

For the above sample document data i want write a method to find and return the document only having ACL key is 123gd. that is

{
     "_id": 1,
     "first_name": "Tom",
     "email": "[email protected]",
     "ACL": {
        123gd: {
          read: true,
          write: false,
        },
        3sg2w: {
          read: true,
          write: false,
        }
     }
}

So how can i write in mongoose to find the specific document

CodePudding user response:

You can do this through $objectToArray, converting the ACL object to an array of k-v tuple. Then you can use $anyElementTrue to check for any k being 123gd

db.collection.find({
  $expr: {
    "$anyElementTrue": {
      "$map": {
        "input": {
          "$objectToArray": "$ACL"
        },
        "as": "kv",
        "in": {
          $eq: [
            "$$kv.k",
            "123gd"
          ]
        }
      }
    }
  }
})

Here is the Mongo Playground for your reference.

  • Related