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 $where operator evaluates a JavaScript function for each document.
  • toString() converts ObjectId values to comparable strings.
  • Only documents where _id matches Details.id are 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.

Updated on: 2026-03-15T01:49:34+05:30

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements