为此,请使用$size运算符。首先让我们创建一个包含文档的集合-
> 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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> 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" : [ ] }
以下是检查列表是否为空的查询-
> db.checkIfListIsNotEmptyDemo.find({'UserFriendGroup': {'$not': {'$size': 0}}});
这将产生以下输出-
{ "_id" : ObjectId("5cdd99e8bf3115999ed511f7"), "UserFriendGroup" : [ "John", "David" ] } { "_id" : ObjectId("5cdd99e9bf3115999ed511f8"), "UserFriendGroup" : [ "Carol" ] } { "_id" : ObjectId("5cdd99f2bf3115999ed511fa"), "UserFriendGroup" : [ null ] }