Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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: 0matches arrays with zero elements. -
$notnegates the condition to find non-empty arrays. - Arrays containing
nullvalues 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.
Advertisements
