Find MongoDB records where array field is not empty?

To find MongoDB records where an array field is not empty, use the $ne (not equal) operator with an empty array []. You can also combine it with $exists to ensure the field exists and is not empty.

Syntax

db.collection.find({
    "arrayField": { $exists: true, $ne: [] }
});

Sample Data

db.arrayFieldIsNotEmptyDemo.insertMany([
    {"StudentName": "Larry", "StudentTechnicalSubject": ["Java", "C"]},
    {"StudentName": "Mike", "StudentTechnicalSubject": []},
    {"StudentName": "Sam", "StudentTechnicalSubject": ["MongoDB"]},
    {"StudentName": "Carol", "StudentTechnicalSubject": []},
    {"StudentName": "David", "StudentTechnicalSubject": ["MySQL", "SQL Server"]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c76fe2f1e9c5dd6f1f78291"),
        ObjectId("5c76fe3b1e9c5dd6f1f78292"),
        ObjectId("5c76fe491e9c5dd6f1f78293"),
        ObjectId("5c76fe521e9c5dd6f1f78294"),
        ObjectId("5c76fe661e9c5dd6f1f78295")
    ]
}

View All Documents

db.arrayFieldIsNotEmptyDemo.find().pretty();
{
    "_id": ObjectId("5c76fe2f1e9c5dd6f1f78291"),
    "StudentName": "Larry",
    "StudentTechnicalSubject": ["Java", "C"]
}
{
    "_id": ObjectId("5c76fe3b1e9c5dd6f1f78292"),
    "StudentName": "Mike",
    "StudentTechnicalSubject": []
}
{
    "_id": ObjectId("5c76fe491e9c5dd6f1f78293"),
    "StudentName": "Sam",
    "StudentTechnicalSubject": ["MongoDB"]
}
{
    "_id": ObjectId("5c76fe521e9c5dd6f1f78294"),
    "StudentName": "Carol",
    "StudentTechnicalSubject": []
}
{
    "_id": ObjectId("5c76fe661e9c5dd6f1f78295"),
    "StudentName": "David",
    "StudentTechnicalSubject": ["MySQL", "SQL Server"]
}

Find Records with Non-Empty Arrays

db.arrayFieldIsNotEmptyDemo.find({
    "StudentTechnicalSubject": { $exists: true, $ne: [] }
}).pretty();
{
    "_id": ObjectId("5c76fe2f1e9c5dd6f1f78291"),
    "StudentName": "Larry",
    "StudentTechnicalSubject": ["Java", "C"]
}
{
    "_id": ObjectId("5c76fe491e9c5dd6f1f78293"),
    "StudentName": "Sam",
    "StudentTechnicalSubject": ["MongoDB"]
}
{
    "_id": ObjectId("5c76fe661e9c5dd6f1f78295"),
    "StudentName": "David",
    "StudentTechnicalSubject": ["MySQL", "SQL Server"]
}

Key Points

  • $ne: [] excludes documents where the array field is empty
  • $exists: true ensures the field exists in the document
  • This query returns only documents with at least one element in the array

Conclusion

Use { $exists: true, $ne: [] } to find MongoDB documents with non-empty array fields. This combination ensures the field exists and contains at least one element.

Updated on: 2026-03-14T23:58:07+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements