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
Selected Reading
MongoDB query to exclude if id is equal to a document field array value
To exclude documents where the id field equals any value in a document's array field, use $expr with $not and $in operators. This allows field-to-field comparison within the same document.
Syntax
db.collection.find({
$expr: {
$not: {
$in: ["$idField", "$arrayField"]
}
}
});
Sample Data
Let us create a collection with documents ?
db.collection.insertMany([
{
id: "101",
subjectid: ["102"]
},
{
id: "102",
subjectid: ["102"]
}
]);
Display All Documents
First, let's see all documents in the collection ?
db.collection.find();
[
{
"_id": ObjectId("5a934e000102030405000000"),
"id": "101",
"subjectid": ["102"]
},
{
"_id": ObjectId("5a934e000102030405000001"),
"id": "102",
"subjectid": ["102"]
}
]
Exclude Matching Documents
Query to exclude documents where id exists in the subjectid array ?
db.collection.find({
$expr: {
$not: {
$in: ["$id", "$subjectid"]
}
}
});
[
{
"_id": ObjectId("5a934e000102030405000000"),
"id": "101",
"subjectid": ["102"]
}
]
How It Works
-
$exprenables field-to-field comparison using aggregation expressions -
$inchecks if theidvalue exists in thesubjectidarray -
$notnegates the condition, returning documents whereidis NOT in the array
Conclusion
Use $expr with $not and $in to exclude documents based on field-to-array comparisons. This pattern is useful for filtering out self-referential or circular relationships in your data.
Advertisements
