Get all the MongoDB documents but not the ones with two given criteria's?

To get all MongoDB documents except those matching specific criteria, use the $ne operator for a single criterion or the $nin operator for multiple criteria exclusion.

Syntax

Single Criterion Exclusion:

db.collection.find({field: {$ne: "value"}});

Multiple Criteria Exclusion:

db.collection.find({field: {$nin: ["value1", "value2"]}});

Sample Data

Let us create a collection with sample documents ?

db.findAllExceptFromOneOrtwoDemo.insertMany([
    {"StudentName": "Larry", "StudentSubjectName": "Java"},
    {"StudentName": "Chris", "StudentSubjectName": "C++"},
    {"StudentName": "Robert", "StudentSubjectName": "C"},
    {"StudentName": "David", "StudentSubjectName": "Python"}
]);

Display all documents in the collection ?

db.findAllExceptFromOneOrtwoDemo.find();
{
    "_id": ObjectId("5c993d82330fd0aa0d2fe4d2"),
    "StudentName": "Larry",
    "StudentSubjectName": "Java"
}
{
    "_id": ObjectId("5c993d8f330fd0aa0d2fe4d3"),
    "StudentName": "Chris",
    "StudentSubjectName": "C++"
}
{
    "_id": ObjectId("5c993d99330fd0aa0d2fe4d4"),
    "StudentName": "Robert",
    "StudentSubjectName": "C"
}
{
    "_id": ObjectId("5c993da4330fd0aa0d2fe4d5"),
    "StudentName": "David",
    "StudentSubjectName": "Python"
}

Case 1: Exclude Single Criterion Using $ne

Find all documents except those with StudentSubjectName as "C" ?

db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName: {$ne: "C"}});
{
    "_id": ObjectId("5c993d82330fd0aa0d2fe4d2"),
    "StudentName": "Larry",
    "StudentSubjectName": "Java"
}
{
    "_id": ObjectId("5c993d8f330fd0aa0d2fe4d3"),
    "StudentName": "Chris",
    "StudentSubjectName": "C++"
}
{
    "_id": ObjectId("5c993da4330fd0aa0d2fe4d5"),
    "StudentName": "David",
    "StudentSubjectName": "Python"
}

Case 2: Exclude Multiple Criteria Using $nin

Find all documents except those with StudentSubjectName as "C++" or "Python" ?

db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName: {$nin: ["C++", "Python"]}});
{
    "_id": ObjectId("5c993d82330fd0aa0d2fe4d2"),
    "StudentName": "Larry",
    "StudentSubjectName": "Java"
}
{
    "_id": ObjectId("5c993d99330fd0aa0d2fe4d4"),
    "StudentName": "Robert",
    "StudentSubjectName": "C"
}

Key Points

  • $ne excludes documents where the field equals the specified value
  • $nin excludes documents where the field matches any value in the array
  • Both operators return all documents that do not match the specified criteria

Conclusion

Use $ne for single value exclusion and $nin for multiple value exclusion. These operators effectively filter out unwanted documents while returning all others that meet your query requirements.

Updated on: 2026-03-15T00:27:16+05:30

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements