Check if a list is not empty in MongoDB?

To check if a list is not empty in MongoDB, use the $not operator combined with $size to exclude arrays with zero elements. This returns documents where the array field contains at least one element.

Syntax

db.collection.find({
    "arrayField": { "$not": { "$size": 0 } }
});

Sample Data

db.checkIfListIsNotEmptyDemo.insertMany([
    { "UserFriendGroup": ["John", "David"] },
    { "UserFriendGroup": ["Carol"] },
    { "UserFriendGroup": [] },
    { "UserFriendGroup": [null] },
    { "UserFriendGroup": [] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cdd99e8bf3115999ed511f7"),
        ObjectId("5cdd99e9bf3115999ed511f8"),
        ObjectId("5cdd99ebbf3115999ed511f9"),
        ObjectId("5cdd99f2bf3115999ed511fa"),
        ObjectId("5cdd99f6bf3115999ed511fb")
    ]
}

View All Documents

db.checkIfListIsNotEmptyDemo.find().pretty();
{
    "_id": ObjectId("5cdd99e8bf3115999ed511f7"),
    "UserFriendGroup": [
        "John",
        "David"
    ]
}
{
    "_id": ObjectId("5cdd99e9bf3115999ed511f8"),
    "UserFriendGroup": [
        "Carol"
    ]
}
{ "_id": ObjectId("5cdd99ebbf3115999ed511f9"), "UserFriendGroup": [] }
{
    "_id": ObjectId("5cdd99f2bf3115999ed511fa"),
    "UserFriendGroup": [
        null
    ]
}
{ "_id": ObjectId("5cdd99f6bf3115999ed511fb"), "UserFriendGroup": [] }

Check If List Is Not Empty

db.checkIfListIsNotEmptyDemo.find({
    'UserFriendGroup': { '$not': { '$size': 0 } }
});
{ "_id": ObjectId("5cdd99e8bf3115999ed511f7"), "UserFriendGroup": ["John", "David"] }
{ "_id": ObjectId("5cdd99e9bf3115999ed511f8"), "UserFriendGroup": ["Carol"] }
{ "_id": ObjectId("5cdd99f2bf3115999ed511fa"), "UserFriendGroup": [null] }

Key Points

  • $size: 0 matches arrays with zero elements.
  • $not negates the condition to find non-empty arrays.
  • Arrays containing null values are considered non-empty.

Conclusion

Use { "$not": { "$size": 0 } } to efficiently find documents with non-empty arrays. This approach excludes only arrays with zero elements, treating arrays with null values as non-empty.

Updated on: 2026-03-15T01:25:23+05:30

498 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements