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, finding all documents where property id equals to record id?
To find all documents where a property id equals the record's _id in MongoDB, use the $where operator with a JavaScript function that compares the field values after converting them to strings.
Syntax
db.collection.find({
$where: function(){
return this._id.toString() == this.fieldName.toString();
}
});
Sample Data
db.demo69.insertMany([
{
"_id": ObjectId("507c7f79bcf86cd7994f6c0e"),
"Details": {
"id": ObjectId("507c7f79bcf86cd7994f6c0e")
}
},
{
"_id": ObjectId("507c7f79bcf86cd7994f6c0f"),
"Details": {
"id": ObjectId("507c7f79bcf86cd7994f6c0a")
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("507c7f79bcf86cd7994f6c0e"),
ObjectId("507c7f79bcf86cd7994f6c0f")
]
}
Let's display all documents to see the data structure ?
db.demo69.find();
{ "_id": ObjectId("507c7f79bcf86cd7994f6c0e"), "Details": { "id": ObjectId("507c7f79bcf86cd7994f6c0e") } }
{ "_id": ObjectId("507c7f79bcf86cd7994f6c0f"), "Details": { "id": ObjectId("507c7f79bcf86cd7994f6c0a") } }
Example: Find Documents Where Details.id Equals _id
db.demo69.find({
$where: function(){
return this._id.toString() == this.Details.id.toString();
}
}).pretty();
{
"_id": ObjectId("507c7f79bcf86cd7994f6c0e"),
"Details": {
"id": ObjectId("507c7f79bcf86cd7994f6c0e")
}
}
How It Works
- The
$whereoperator evaluates a JavaScript function for each document. -
toString()converts ObjectId values to comparable strings. - Only documents where
_idmatchesDetails.idare returned.
Conclusion
Use $where with JavaScript comparison to find documents where nested property values match the document's _id. Convert ObjectId values to strings for proper equality comparison.
Advertisements
