G.Mounika
G.Mounika

Reputation: 425

How to fetch the documents where the field in array is not equal to particular value in MongoDB?

Documents in database collection are in below format

{
  _id:1,
  a: [{b:1, c:2, d:3}, {b:2, c:3, d:4}]
},
{
  _id:2,
  a: [{b:2, c:2, d:4}, {b:3, c:5, d:4}]
},
{
  _id:3,
  a: [{b:4, c:4, d:3}, {b:5, c:3, d:2}]
}

From the above documents I need to get only the documents where 'b!=4' that means only _id=1 & _id=2 should be returned.

For this I have tried the below query but I didn't get the expected result. Instead I got all documents.

db.collectionname.find({a: {$nin: [{b: 4}]}})

Any alternate solution, please help me out.

Upvotes: 1

Views: 1039

Answers (1)

felix
felix

Reputation: 9285

you're using the wrong operator. You should use $ne instead of **$nin**.

From mongodb documentation:

$nin selects the documents where:

  • the field value is not in the specified array or
  • the field does not exist.

so the query

db.collectionname.find({a: {$nin: [{b: 4}]}})

will look for document with array a not containing this exact document: {b: 4} . Here the 3 documents match because inner documents has b and c keys, wheras {b: 4} hasn't.

For a single field check, you should use $ne

The correct query is

db.collectionname.find({"a.b": {$ne: 4}})

This returns:

{ "_id" : 1, "a" : [ { "b" : 1, "c" : 2, "d" : 3 }, { "b" : 2, "c" : 3, "d" : 4 } ] }
{ "_id" : 2, "a" : [ { "b" : 2, "c" : 2, "d" : 4 }, { "b" : 3, "c" : 5, "d" : 4 } ] }

Upvotes: 3

Related Questions