0

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

1

1 Answer 1

1

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 }
)
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.