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 work with time series data in MongoDB?
- How to check the version of MongoDB?
- How to use watch in MongoDB?
- How to update an array element in MongoDB?
- How to use unwind in MongoDB?
- How to use triggers in MongoDB?
- How to update many documents in MongoDB?
- How to use transactions in MongoDB?
- How to rename a field in MongoDB?
- How to select specific fields in MongoDB query?
See more codes...