MongoDB: nin and in not working together in $elemMatch to fetch documents having subjects "MongoDB", but not "Java

To fetch documents containing "MongoDB" but not "Java" in an array field, use the $and operator with $in and $nin operators. The $elemMatch operator is not needed since we're checking the entire array for value presence.

Syntax

db.collection.find({
    $and: [
        { "arrayField": { $in: ["requiredValue"] } },
        { "arrayField": { $nin: ["excludedValue"] } }
    ]
});

Sample Data

db.demo140.insertMany([
    { "Id": 101, "Subjects": ["MongoDB", "MySQL"] },
    { "Id": 102, "Subjects": ["MongoDB", "Java"] },
    { "Id": 103, "Subjects": ["MongoDB", "PL/SQL"] },
    { "Id": 104, "Subjects": ["MongoDB", "SQL Server"] },
    { "Id": 105, "Subjects": ["C", "C++"] }
]);

Display All Documents

db.demo140.find();
{ "_id": ObjectId("5e31c149fdf09dd6d08539a9"), "Id": 101, "Subjects": ["MongoDB", "MySQL"] }
{ "_id": ObjectId("5e31c14cfdf09dd6d08539aa"), "Id": 102, "Subjects": ["MongoDB", "Java"] }
{ "_id": ObjectId("5e31c157fdf09dd6d08539ab"), "Id": 103, "Subjects": ["MongoDB", "PL/SQL"] }
{ "_id": ObjectId("5e31c163fdf09dd6d08539ac"), "Id": 104, "Subjects": ["MongoDB", "SQL Server"] }
{ "_id": ObjectId("5e31c16ffdf09dd6d08539ad"), "Id": 105, "Subjects": ["C", "C++"] }

Example: Find MongoDB but Not Java

Query to fetch documents having "MongoDB" but not "Java" in the Subjects array ?

db.demo140.find({
    $and: [
        { Subjects: { $in: ["MongoDB"] } },
        { Subjects: { $nin: ["Java"] } }
    ]
});
[
    {
        "_id": ObjectId("5e31c149fdf09dd6d08539a9"),
        "Id": 101,
        "Subjects": ["MongoDB", "MySQL"]
    },
    {
        "_id": ObjectId("5e31c157fdf09dd6d08539ab"),
        "Id": 103,
        "Subjects": ["MongoDB", "PL/SQL"]
    },
    {
        "_id": ObjectId("5e31c163fdf09dd6d08539ac"),
        "Id": 104,
        "Subjects": ["MongoDB", "SQL Server"]
    }
]

How It Works

  • $in ensures the array contains "MongoDB"
  • $nin ensures the array does not contain "Java"
  • $and combines both conditions
  • $elemMatch is unnecessary for this use case

Conclusion

Use $and with $in and $nin to filter arrays by including required values while excluding unwanted ones. This approach effectively handles inclusion and exclusion conditions on array fields without needing $elemMatch.

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

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements