How can I use 'Not Like' operator in MongoDB?

In MongoDB, there is no direct 'NOT LIKE' operator as found in SQL. Instead, use the $not operator combined with regular expressions to achieve similar functionality for pattern matching exclusion.

Syntax

db.collection.find({ 
    fieldName: { $not: /pattern/ } 
});

Sample Data

db.notLikeOperatorDemo.insertMany([
    { "StudentName": "John Doe" },
    { "StudentName": "John Smith" },
    { "StudentName": "John Taylor" },
    { "StudentName": "Carol Taylor" },
    { "StudentName": "David Miller" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c8a29c393b406bd3df60dfc"),
        ObjectId("5c8a29cc93b406bd3df60dfd"),
        ObjectId("5c8a29df93b406bd3df60dfe"),
        ObjectId("5c8a2a1693b406bd3df60dff"),
        ObjectId("5c8a2a2693b406bd3df60e00")
    ]
}

Display All Documents

db.notLikeOperatorDemo.find();
{ "_id": ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName": "John Doe" }
{ "_id": ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName": "John Smith" }
{ "_id": ObjectId("5c8a29df93b406bd3df60dfe"), "StudentName": "John Taylor" }
{ "_id": ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName": "Carol Taylor" }
{ "_id": ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName": "David Miller" }

Method 1: Exclude Exact String Match

Find all students whose name is NOT exactly "John Taylor" :

db.notLikeOperatorDemo.find({
    StudentName: { $not: /^John Taylor$/ }
});
{ "_id": ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName": "John Doe" }
{ "_id": ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName": "John Smith" }
{ "_id": ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName": "Carol Taylor" }
{ "_id": ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName": "David Miller" }

Method 2: Exclude Partial String Match

Find all students whose name does NOT contain "John" :

db.notLikeOperatorDemo.find({
    StudentName: { $not: /John/ }
});
{ "_id": ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName": "Carol Taylor" }
{ "_id": ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName": "David Miller" }

Key Points

  • $not negates the regular expression match
  • Use ^ for start of string and $ for end of string anchors
  • Regular expressions are case-sensitive by default

Conclusion

MongoDB's $not operator with regular expressions provides flexible pattern exclusion capabilities similar to SQL's NOT LIKE operator. Combine it with regex anchors for precise matching control.

Updated on: 2026-03-15T00:07:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements