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 - How to check for equality in collection and in embedded document?
To check for equality between a field in the main collection and a field in an embedded document, use the $where operator with JavaScript expressions. This allows you to compare values across different nesting levels within the same document.
Syntax
db.collection.find({
$where: 'this.fieldName === this.embeddedDoc.fieldName'
});
Sample Data
db.demo292.insertMany([
{
"FirstName": "Chris",
"LastName": "Brown",
"Friend": {
"FirstName": "David",
"LastName": "Miller"
}
},
{
"FirstName": "John",
"LastName": "Doe",
"Friend": {
"FirstName": "Mike",
"LastName": "Doe"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4c10aa5d93261e4bc9ea30"),
ObjectId("5e4c10dc5d93261e4bc9ea31")
]
}
View Sample Data
db.demo292.find();
{
"_id": ObjectId("5e4c10aa5d93261e4bc9ea30"),
"FirstName": "Chris",
"LastName": "Brown",
"Friend": {
"FirstName": "David",
"LastName": "Miller"
}
}
{
"_id": ObjectId("5e4c10dc5d93261e4bc9ea31"),
"FirstName": "John",
"LastName": "Doe",
"Friend": {
"FirstName": "Mike",
"LastName": "Doe"
}
}
Example: Find Documents Where LastName Equals Friend's LastName
db.demo292.find({
$where: 'this.Friend.LastName === this.LastName'
});
{
"_id": ObjectId("5e4c10dc5d93261e4bc9ea31"),
"FirstName": "John",
"LastName": "Doe",
"Friend": {
"FirstName": "Mike",
"LastName": "Doe"
}
}
Key Points
- Use
$wherewith JavaScript expressions to compare fields across different document levels. - Access embedded document fields using dot notation:
this.embeddedDoc.field -
$whereevaluates JavaScript expressions for each document, making it slower than other operators.
Conclusion
The $where operator enables equality checks between collection fields and embedded document fields using JavaScript expressions. While powerful for complex comparisons, use it judiciously as it can impact query performance.
Advertisements
