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
    Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Cuong Le Ngoc Apr 17 '20 at 08:51

1 Answers1

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 }
)
Kevin Smith
  • 13,746
  • 4
  • 52
  • 77