Check if a list is not empty in MongoDB?


For this, use the $size operator. Let us first create a collection with documents −

> db.checkIfListIsNotEmptyDemo.insertOne({"UserFriendGroup":["John","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdd99e8bf3115999ed511f7")
}
> db.checkIfListIsNotEmptyDemo.insertOne({"UserFriendGroup":["Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdd99e9bf3115999ed511f8")
}
> db.checkIfListIsNotEmptyDemo.insertOne({"UserFriendGroup":[]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdd99ebbf3115999ed511f9")
}
> db.checkIfListIsNotEmptyDemo.insertOne({"UserFriendGroup":[null]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdd99f2bf3115999ed511fa")
}
> db.checkIfListIsNotEmptyDemo.insertOne({"UserFriendGroup":[]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdd99f6bf3115999ed511fb")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.checkIfListIsNotEmptyDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cdd99e8bf3115999ed511f7"),
   "UserFriendGroup" : [
      "John",
      "David"
   ]
}
{
   "_id" : ObjectId("5cdd99e9bf3115999ed511f8"),
   "UserFriendGroup" : [
      "Carol"
   ]
}
{ "_id" : ObjectId("5cdd99ebbf3115999ed511f9"), "UserFriendGroup" : [ ] }
{
   "_id" : ObjectId("5cdd99f2bf3115999ed511fa"),
   "UserFriendGroup" : [
      null
   ]
}
{ "_id" : ObjectId("5cdd99f6bf3115999ed511fb"), "UserFriendGroup" : [ ] }

Following is the query to check if a list is not empty −

> db.checkIfListIsNotEmptyDemo.find({'UserFriendGroup': {'$not': {'$size': 0}}});

This will produce the following output −

{ "_id" : ObjectId("5cdd99e8bf3115999ed511f7"), "UserFriendGroup" : [ "John", "David" ] }
{ "_id" : ObjectId("5cdd99e9bf3115999ed511f8"), "UserFriendGroup" : [ "Carol" ] }
{ "_id" : ObjectId("5cdd99f2bf3115999ed511fa"), "UserFriendGroup" : [ null ] }

Updated on: 30-Jul-2019

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements