Syntax error Match MongoDB documents with fields not containing values in array?

Match MongoDB documents with fields not containing values in array?



To match documents with fields not containing values in array, use $nin. Let us create a collection with documents −

> db.demo180.insertOne({"Scores":["80","90","110"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3988a69e4f06af551997fb")
}
> db.demo180.insertOne({"Scores":["110","70","60"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3988b79e4f06af551997fc")
}
> db.demo180.insertOne({"Scores":["40","70","1010"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3988cc9e4f06af551997fd")
}

Display all documents from a collection with the help of find() method −

> db.demo180.find();

This will produce the following output −

{ "_id" : ObjectId("5e3988a69e4f06af551997fb"), "Scores" : [ "80", "90", "110" ] }
{ "_id" : ObjectId("5e3988b79e4f06af551997fc"), "Scores" : [ "110", "70", "60" ] }
{ "_id" : ObjectId("5e3988cc9e4f06af551997fd"), "Scores" : [ "40", "70", "1010" ] }

Following is the query to match documents with fields not containing values in array −

> db.demo180.aggregate({ "$match": { "Scores": { "$nin": ["110","90"] } } }).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e3988cc9e4f06af551997fd"),
   "Scores" : [ "40", "70", "1010" ]
}
Updated on: 2020-03-27T07:53:35+05:30

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements