Find document in MongoDB where at least one item from an array is not in the other?

To find documents in MongoDB where at least one item from an array is not in another specified set, use the $nin operator or regex patterns to match arrays containing elements outside your target list.

Syntax

// Using $nin operator
db.collection.find({ "arrayField": { $nin: ["value1", "value2"] } });

// Using regex for negative lookahead
db.collection.find({ "arrayField": /^(?!value1|value2)/ });

Sample Data

db.demo228.insertMany([
    { "Subjects": ["MongoDB", "Java"] },
    { "Subjects": ["MongoDB", "Java", "MySQL"] },
    { "Subjects": ["Python", "JavaScript"] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3fa51f03d395bdc213473b"),
        ObjectId("5e3fa52c03d395bdc213473c"),
        ObjectId("5e3fa53d03d395bdc213473d")
    ]
}

Method 1: Using Regex (Original Approach)

Find documents where at least one array element is NOT "MongoDB" or "Java" ?

db.demo228.find({ "Subjects": /^(?!MongoDB|Java)/ });
{ "_id": ObjectId("5e3fa52c03d395bdc213473c"), "Subjects": ["MongoDB", "Java", "MySQL"] }
{ "_id": ObjectId("5e3fa53d03d395bdc213473d"), "Subjects": ["Python", "JavaScript"] }

Method 2: Using $nin Operator (Recommended)

A clearer approach using $nin to find arrays with elements not in the specified list ?

db.demo228.find({ "Subjects": { $nin: ["MongoDB", "Java"] } });
{ "_id": ObjectId("5e3fa52c03d395bdc213473c"), "Subjects": ["MongoDB", "Java", "MySQL"] }
{ "_id": ObjectId("5e3fa53d03d395bdc213473d"), "Subjects": ["Python", "JavaScript"] }

Key Points

  • The regex /^(?!MongoDB|Java)/ uses negative lookahead to match array elements that don't start with the specified values.
  • $nin operator is more readable and finds documents where the array contains at least one element not in the specified list.
  • Both methods return documents containing elements outside the target set.

Conclusion

Use $nin operator for cleaner queries when finding arrays with elements not in a specified list. Regex with negative lookahead provides more pattern-matching flexibility but is less readable for simple exclusions.

Updated on: 2026-03-15T02:00:29+05:30

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements