1

I want to get all document where (B.arrayC.X == 128 AND B.arrayC.Y == 'PENDING')

Collection records are like below which contains an Array of Embedded Documents.

{
    "_id" : NumberLong(1),
    "A" : NumberLong(0),
    "B" : {
        "arrayC" : [ 
            {
                "X" : NumberLong(128),
                "Y" : "COMPLETED",
                "Z" : NumberLong(50)
            }, 
            {
                "X" : NumberLong(109),
                "Y" : "PENDING",
                "Z" : NumberLong(0)
            }
        ]
    }
},
{
    "_id" : NumberLong(2),
    "A" : NumberLong(0),
    "B" : {
        "arrayC" : [ 
            {
                "X" : NumberLong(128),
                "Y" : "PENDING",
                "Z" : NumberLong(50)
            }, 
            {
                "X" : NumberLong(109),
                "Y" : "PENDING",
                "Z" : NumberLong(0)
            }
        ]
    }
}

I have tried the below queries, all queries are returning none PENDING jobs.

db.getCollection('demo').find({"B.arrayC.X" : 128, "B.arrayC.Y" : "PENDING"})

db.getCollection('demo').find({"$and":[{"B.arrayC.X" : 128, "B.arrayC.Y" : "PENDING"}])

db.getCollection('demo').find({"$and":[{"B.arrayC.X" : 128}, {"B.arrayC.Y" : "PENDING"}])

What I understand is MongoDB returning _id 1 record due to B.arrayC.X record with 109 id have "PENDING" state in it. What should be the correct query?

1 Answer 1

2

What I understand is MongoDB returning _id 1 record due to B.arrayC.X record with 109 id have "PENDING" state in it. What should be the correct query?

As per your try both the field's conditions are separate and it will result document if X satisfied condition in any element of arrayC and if Y satisfied condition in any element of arrayC,

Try $elemMatch to match all the fields in every single element,

db.getCollection('demo').find({
  "B.arrayC": {
    $elemMatch: {
      X: 128,
      Y: "PENDING"
    }
  }
})

Playground

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.