Reputation: 9738
i have the following document in a collection:
{
"_id" : 101,
"students" : [
{
"name" : "john",
"age" : 10,
"city":'CA'
},
{
"name" : "danial",
"age" : 15,
"city":'KA'
}
]
}
{
"_id" : 102,
"students" : [
{
"name" : "adam",
"age" : 20,
"city":'NY'
},
{
"name" : "johnson",
"age" : 12,
"city":'CA'
}
]
}
And i fire the following query:
db.data.find({'students.city':'CA'})
This returns me "students" objects from both the documents, as one instance matches the filter ("city"; 'CA') in both.
However, i desire to only get the matching array in the result. That is, i want the following result:
{
"_id" : 101,
"students" : [
{
"name" : "john",
"age" : 10,
"city":'CA'
}
]
}
{
"_id" : 102,
"students" : [
{
"name" : "johnson",
"age" : 12,
"city":'CA'
}
]
}
Please help.
Upvotes: 0
Views: 2911
Reputation: 20683
You need to use $elemMatch
in your projection:
> db.data.find({'students.city':'CA'},{ students:{ $elemMatch:{'city':'CA'} }})
{ "_id" : 101, "students" : [ { "name" : "john", "age" : 10, "city" : "CA" } ] }
{ "_id" : 102, "students" : [ { "name" : "johnson", "age" : 12, "city" : "CA" } ] }
Btw: I'd strongly suggest reading the Open letter to students with homework problems.
Upvotes: 3
Reputation: 4328
I think you should use an aggregation operation.
Here you have the documentation: https://docs.mongodb.org/manual/aggregation/
And a similar question: Retrieve only the queried element in an object array in MongoDB collection
Upvotes: 0