Reputation: 23
collection is
{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }
query is
db.survey.find(
{ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)
it returns
{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" : "xyz", "score" : 8 } ] }
but i also wanted to ignore { "product" : "abc", "score" : 7 } when returning the json.i tried other match aswel still it returns with other records.how to handle?Kindly help thanks
Upvotes: 0
Views: 278
Reputation: 14436
You need to project the matching results with a positional operator $
, else it will always return the full document that matched the query. (hence why you're getting the full results).
db.survey.find(
{ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } },
{ "results.$": 1 }
)
Upvotes: 1