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$sizeoperator returns the number of elements in an array. If the array is empty, the$sizeoperator will return 0.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to specify a password for MongoDB Docker?
- How to drop a database in MongoDB?
- How to bind IP addresses for MongoDB server?
- How to use unwind in MongoDB?
- How to use the limit operator in MongoDB?
- How to use the MongoDB distinct operator?
- How to use transactions in MongoDB?
- How to set MongoDB oplog?
- How to join two collections in MongoDB?
See more codes...