2

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})
    
2
  • can you add the expected output? in JSON? Commented Nov 11, 2021 at 20:30
  • If iseligible doesnt exist for any of the items, I need that complete document to be displayed. For eg., have 2 documents: { "_id" : 12345, "orderItems" : [ { "itemId" : 45678, "isAvailable" : true, "isEligible" " false }, { "itemId" : 87653, "isAvailable" : true } ] } { "_id" : 12346, "orderItems" : [ { "itemId" : 45678, "isAvailable" : true, "isEligible" " false }, { "itemId" : 87653, "isEligibe": false, "isAvailable" : true } ] } In the above example, the output should return first document since it doesnt contain isEligible for one of the item Commented Nov 11, 2021 at 20:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.