MongoDB query for documents whose array elements does not have a specific value


For such cases, use $elemMatch. This operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Let us create a collection with documents −

> db.demo239.insertOne(
...   {
...      "Name" : "Chris",
...      "details" : [
...         { "DueDate" : new ISODate("2019-01-21"), "ProductPrice" : 1270 },
...         { "DueDate" : new ISODate("2020-02-12"), "ProductPrice" : 2000 }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e441c6bf4cebbeaebec5157")
}
> db.demo239.insertOne(
...   {
...      "Name" : "David",
...      "details" : [
...         { "DueDate" : new ISODate("2018-11-11"), "ProductPrice" : 1450},
...         { "DueDate" : new ISODate("2020-02-12") }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e441c6cf4cebbeaebec5158")
}

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

> db.demo239.find();

This will produce the following output −

{
   "_id" : ObjectId("5e441c6bf4cebbeaebec5157"), "Name" : "Chris", "details" : [
      { "DueDate" : ISODate("2019-01-21T00:00:00Z"), "ProductPrice" : 1270 },
      { "DueDate" : ISODate("2020-02-12T00:00:00Z"), "ProductPrice" : 2000 }
   ]
}
{
   "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [
      { "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 },
      { "DueDate" : ISODate("2020-02-12T00:00:00Z") }
   ]
}

Following is the query to fetch documents whose array elements does not have a specific value −

> db.demo239.find({ "details": { "$elemMatch": { "DueDate": { "$exists": true }, "ProductPrice": { "$exists": false } } } })

This will produce the following output −

{ "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [ { "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 }, { "DueDate" : ISODate("2020-02-12T00:00:00Z") } ] }

Updated on: 30-Mar-2020

417 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements