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

  • $expr enables field-to-field comparison using aggregation expressions
  • $in checks if the id value exists in the subjectid array
  • $not negates the condition, returning documents where id is 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.

Updated on: 2026-03-15T01:52:40+05:30

889 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements