Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find documents with arrays not containing a document with a particular field value in MongoDB?
To find documents with arrays not containing a document with a particular field value in MongoDB, use the $nin operator with dot notation to specify the array field and value to exclude.
Syntax
db.collection.find({"arrayField.fieldName": {$nin: [value]}})
Sample Data
Let us create a collection with student documents containing nested arrays ?
db.documentWithAParticularFieldValueDemo.insertMany([
{
"StudentId": 101,
"StudentDetails": [
{
"TheoryMarks": 78,
"PracticalMarks": 91
},
{
"TheoryMarks": 75,
"PracticalMarks": 75
}
]
},
{
"StudentId": 102,
"StudentDetails": [
{
"TheoryMarks": 91,
"PracticalMarks": 91
},
{
"TheoryMarks": 75,
"PracticalMarks": 75
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8edab72f684a30fbdfd586"),
ObjectId("5c8edaf12f684a30fbdfd587")
]
}
Display all documents from the collection ?
db.documentWithAParticularFieldValueDemo.find().pretty();
{
"_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
}
]
}
Example: Find Documents Without TheoryMarks of 78
Find documents where the StudentDetails array does not contain any document with TheoryMarks equal to 78 ?
db.documentWithAParticularFieldValueDemo.find({'StudentDetails.TheoryMarks': {$nin: [78]}}).pretty();
{
"_id": ObjectId("5c8edaf12f684a30fbdfd587"),
"StudentId": 102,
"StudentDetails": [
{
"TheoryMarks": 91,
"PracticalMarks": 91
},
{
"TheoryMarks": 75,
"PracticalMarks": 75
}
]
}
How It Works
The $nin operator returns documents where the specified field value is not in the given array of values. When used with dot notation on nested arrays, it excludes documents containing any sub-document with the matching field value.
Conclusion
Use $nin with dot notation to find documents whose arrays do not contain specific field values. This operator is effective for filtering out documents based on nested array content in MongoDB.
