Find documents with arrays not containing a document with a particular field value in MongoDB?


You can use $nin operator for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.documentWithAParticularFieldValueDemo.insertOne(
   ... {
      ...
      ... "StudentId" : 101,
      ... "StudentDetails" :
      ... [
         ... {
            ... "TheoryMarks": 78,
            ... "PracticalMarks": 91
         ... },
         ... {
            ... "TheoryMarks": 75,
            ... "PracticalMarks": 75
         ... }
      ... ]
   ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8edab72f684a30fbdfd586")
}
> db.documentWithAParticularFieldValueDemo.insertOne(
   ...
   ... { "StudentId" : 102,
      ... "StudentDetails" : [
         ... {
               ... "TheoryMarks": 91,
               ... "PracticalMarks": 91
         ... },
         ... {
            ... "TheoryMarks": 75,
            ... "PracticalMarks": 75
         ... }
      ... ]
   ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8edaf12f684a30fbdfd587")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.documentWithAParticularFieldValueDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c8edab72f684a30fbdfd586"),
   "StudentId" : 101,
   "StudentDetails" : [
      {
         "TheoryMarks" : 78,
         "PracticalMarks" : 91
      },
      {
         "TheoryMarks" : 75,
         "PracticalMarks" : 75
      }
   ]
}
{
   "_id" : ObjectId("5c8edaf12f684a30fbdfd587"),
   "StudentId" : 102,
   "StudentDetails" : [
      {
         "TheoryMarks" : 91,
         "PracticalMarks" : 91
      },
      {
         "TheoryMarks" : 75,
         "PracticalMarks" : 75
      }
   ]
}

Here is the query to find documents with arrays not containing a document with a particular field value in MongoDB −

> db.documentWithAParticularFieldValueDemo.find({'StudentDetails.TheoryMarks': {$nin: [78]}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8edaf12f684a30fbdfd587"),
   "StudentId" : 102,
   "StudentDetails" : [
      {
         "TheoryMarks" : 91,
         "PracticalMarks" : 91
      },
      {
         "TheoryMarks" : 75,
         "PracticalMarks" : 75
      }
   ]
}

Updated on: 30-Jul-2019

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements