CESAR NICOLINI RIVERO
CESAR NICOLINI RIVERO

Reputation: 117

the $elemMatch operator does not work correctly in mongodb

I have the following collection

>db.prueba.find({})
{ "_id" : "A", "requi" : null }
{ "_id" : "D", "requi" : [ "A", "B" ] }
{ "_id" : "E", "requi" : [ "B" ] }
{ "_id" : "B", "requi" : null }
{ "_id" : "C", "requi" : [ "A" ] }

I need each element of the requi field to be in the following array. in this case, the array has only one element

['A']

When I use the operator $elemMatch returns the following

db.prueba.find({requi:{$elemMatch:{$in:['A']}}})
{ "_id" : "D", "requi" : [ "A", "B" ] }
{ "_id" : "C", "requi" : [ "A" ] }

the query must returns only document

{ "_id" : "C", "requi" : [ "A" ] }

please, help me

Upvotes: 2

Views: 363

Answers (1)

Ashh
Ashh

Reputation: 46441

Use $eq operator to find the exact match in the array

db.collection.find({ "requi": { "$eq": [ "A" ] } })

Output

[
  {
    "_id": "C",
    "requi": [
      "A"
    ]
  }
]

Check it here

Upvotes: 4

Related Questions