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 $where with JavaScript expressions to compare fields across different document levels.
  • Access embedded document fields using dot notation: this.embeddedDoc.field
  • $where evaluates 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.

Updated on: 2026-03-15T02:19:18+05:30

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements