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

Time:11-12

I have a JSON in MongoDB and I am trying to check if at least one of the items in the JSON doesn't 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 doesn't 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})
    

CodePudding user response:

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.

  • Related