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

Mongodb- Query to check if a field in the json array exists or not

I have a json in mongodb and I am trying to check if at least one of the items in the json doesnt contain a specific field.
{
"_id" : 12345,
"orderItems" : [
{
"itemId" : 45678,
"isAvailable" : true,
"isEligible" " false
},
{
"itemId" : 87653,
"isAvailable" : true
}
]
}

So in the above json, since the 2nd one under order items doesnt contain iseligible field, I need to get this _id.

I tried the below query so far, which didnt work:
db.getCollection(‘orders’).find({"orderItems.iseligible":{$exists:false})

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

>Solution :

You can use $elemMatch to evaluate the presence of the nested key. Once that’s accomplished, project out the _id value.

db.orders.find({
  orderItems: {
    $elemMatch: {
      "isEligible": {
        $exists: false
      }
    }
  }
},
{
  _id: 1
})

Here is a Mongo playground with the finished code, and a similar SO answer.

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