How to collect only documents which match all values of an array

Hi There,

I need your help, is it possible to collect only documents which all array values matches the query ?

In the example here https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#array-of-embedded-documents

I need a result like this only.

{ "_id" : 3, "results" : [ { "product" : "xyz", "score" : 9 },
                           { "product" : "xyz", "score" : 8 } ] }

An idea ?
Thanks

Hello @muama, Welcome to MongoDB developer forum,

Three is no document with score: 9 in the documentation example.

Your question is not clear can you please elaborate with more examples and details.

Hi,

I know that there is no such example.

In the example we have this query :
db.survey.find(
{ results: { $elemMatch: { product: “xyz”, score: { $gte: 8 } } } }
)

I need to have a result only if all element of the array are true, in the example only if product=xyz and scrore=gte(8).

Normally in the example we should have no result.

Thanks

I am not sure is there any straight approach,

You an try opposite and negative conditions,

  • "results.product": { $ne: "xyz" } and { "results.score": { $lt: 8 } } to select other documents that is not having “xyz” and greater score than 8, and $nor to select not equal to or condition.
db.survey.find({
  $nor: [
    { "results.product": { $ne: "xyz" } },
    { "results.score": { $lt: 8 } }
  ]
})
1 Like

Finnaly, I used this :

db.survey.find({“results”: {
$not: { $elemMatch: {

}}
}})

Thanks for your help