mongodbHow to check if array is empty in MongoDB?
To check if an array is empty in MongoDB, you can use the $size
operator. This operator returns the number of elements in an array. If the array is empty, the $size
operator will return 0.
Example code
db.collection.find( { arrayField: { $size: 0 } } )
Output example
{ "_id" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"), "arrayField" : [] }
Code explanation
db.collection.find()
: This is the MongoDB command to query a collection.{ arrayField: { $size: 0 } }
: This is the query condition to check if the array is empty. The$size
operator returns the number of elements in an array. If the array is empty, the$size
operator will return 0.
Helpful links
More of Mongodb
- How to drop a database in MongoDB?
- How to use watch in MongoDB?
- How to check the version of MongoDB?
- How to use hint in MongoDB?
- How to use triggers in MongoDB?
- How to list MongoDB users?
- How to use unwind in MongoDB?
- How to use MongoDB queue?
- How to work with time series data in MongoDB?
- How to remove a field from MongoDB?
See more codes...