2

Suppose I have the following documents:

{
  "_id": "ID1",
  "A": [
    {
    "a": "abc",
    "b": true
    },
    {
    "a": "abc",
    "b": false
    },
    {
    "a": "def",
    "b": true
    }
  ]
}

{
  "_id": "ID2",
  "A": [
    {
    "a": "abc",
    "b": false
    },
    {
    "a": "abc",
    "b": false
    },
    {
    "a": "def",
    "b": true
    }
  ]
}

How can I adjust my query:

db.collection.aggregate([
  {$match: {"A.a": "abc"}},
  {$project: {A: 1}}
])

So that I match only documetns where there is at least one object in A where A.a=abc AND A.b=true? In this example the outcome would be just:

{
  "_id": "ID1",
  "A": [
    {
    "a": "abc",
    "b": true
    },
    {
    "a": "abc",
    "b": false
    },
    {
    "a": "def",
    "b": true
    }
  ]
}

1 Answer 1

1

You need to use $elemMatch

db.collection.aggregate([
  { $match: { A: { $elemMatch: { a: "abc", b: true }}},
  { $project: { A: 1 }}
])

can use find query as well

db.collection.find(
  { A: { $elemMatch: { a: "abc", b: true }},
  { A: 1 }
)
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.