0

Suppose I have this data:

[
  {
    "_id": 101,
    "name": "ABC",
    "students": [
      {
        "name": "john",
        "age": 10,
        "city": "CA"
      },
      {
        "name": "danial",
        "age": 15,
        "city": "KA"
      }
    ]
  },
  {
    "_id": 102,
    "name": "DEF",
    "students": [
      {
        "name": "adam",
        "age": 20,
        "city": "NY"
      },
      {
        "name": "johnson",
        "age": 12,
        "city": "CA"
      }
    ]
  }
]

Now I want to fetch the name and the students whose city is CA.

What I have done is:

db.collection.find({
  "students.city": "CA"
},
{
  students: {
    $elemMatch: {
      "city": "CA"
    }
  }
})

and it returns:

[
  {
    "_id": 101,
    "students": [
      {
        "age": 10,
        "city": "CA",
        "name": "john"
      }
    ]
  },
  {
    "_id": 102,
    "students": [
      {
        "age": 12,
        "city": "CA",
        "name": "johnson"
      }
    ]
  }
]

But the name is missing i.e. ABC and DEF, how to include that?

Now If I do something like this:

db.collection.find({
  students: {
    $elemMatch: {
      city: "CA"
    }
  }
})

Then it is returning name and as well as students array but it is included those students whose city is not CA.

[
  {
    "_id": 101,
    "name": "ABC",
    "students": [
      {
        "age": 10,
        "city": "CA",
        "name": "john"
      },
      {
        "age": 15,
        "city": "KA",
        "name": "danial"
      }
    ]
  },
  {
    "_id": 102,
    "name": "DEF",
    "students": [
      {
        "age": 20,
        "city": "NY",
        "name": "adam"
      },
      {
        "age": 12,
        "city": "CA",
        "name": "johnson"
      }
    ]
  }
]

Here is the link to the playground https://mongoplayground.net/p/NHHu3GahKoK

1 Answer 1

1

You need to add name: 1 into the projection.

db.collection.find({
  "students.city": "CA"
},
{
  name: 1,
  students: {
    $elemMatch: {
      "city": "CA"
    }
  }
})

Sample Mongo Playground

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

1 Comment

Thanks, sir :) I forgot to include into projection

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.