Add a boolean field true to returned objects, when a specified value is in array. For NULLnor other values, set false.

To add a boolean field true to returned objects when a specified value exists in an array (and false for NULL or missing values), use the $ifNull operator with $setIntersection and $size to check array membership.

Syntax

db.collection.aggregate([
    {
        "$project": {
            "fieldName": {
                "$eq": [
                    {
                        "$size": {
                            "$ifNull": [
                                { "$setIntersection": [ "$arrayField", ["searchValue"] ] },
                                []
                            ]
                        }
                    },
                    1
                ]
            }
        }
    }
])

Sample Data

db.demo542.insertMany([
    {"ListOfName": ["Chris", "David"]},
    {"ListOfName": null},
    {"ListOfName": ["David"]},
    {"Name": "John"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8cabc6ef4dcbee04fbbc17"),
        ObjectId("5e8cabc8ef4dcbee04fbbc18"),
        ObjectId("5e8cabd3ef4dcbee04fbbc19"),
        ObjectId("5e8cabdaef4dcbee04fbbc1a")
    ]
}

View Sample Data

db.demo542.find();
{ "_id": ObjectId("5e8cabc6ef4dcbee04fbbc17"), "ListOfName": [ "Chris", "David" ] }
{ "_id": ObjectId("5e8cabc8ef4dcbee04fbbc18"), "ListOfName": null }
{ "_id": ObjectId("5e8cabd3ef4dcbee04fbbc19"), "ListOfName": [ "David" ] }
{ "_id": ObjectId("5e8cabdaef4dcbee04fbbc1a"), "Name": "John" }

Example: Check for "David" in Arrays

var searchValue = "David";
db.demo542.aggregate([
    {
        "$project": {
            "matched": {
                "$eq": [
                    {
                        "$size": {
                            "$ifNull": [
                                { "$setIntersection": [ "$ListOfName", [searchValue] ] },
                                []
                            ]
                        }
                    },
                    1
                ]
            }
        }
    }
]);
{ "_id": ObjectId("5e8cabc6ef4dcbee04fbbc17"), "matched": true }
{ "_id": ObjectId("5e8cabc8ef4dcbee04fbbc18"), "matched": false }
{ "_id": ObjectId("5e8cabd3ef4dcbee04fbbc19"), "matched": true }
{ "_id": ObjectId("5e8cabdaef4dcbee04fbbc1a"), "matched": false }

How It Works

  • $setIntersection finds common elements between the array and search value
  • $ifNull handles NULL values by returning an empty array []
  • $size counts intersection elements (1 = match found, 0 = no match)
  • $eq compares size to 1, returning true/false

Conclusion

Use $ifNull with $setIntersection to safely check array membership. This approach returns false for NULL values and missing fields, and true only when the specified value exists in the array.

Updated on: 2026-03-15T03:31:08+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements