为此,请使用$ ifNull。它计算一个表达式,如果该表达式的计算结果为非空值,则返回该表达式的值。首先让我们创建一个包含文档的集合-
> db.demo542.insertOne({"ListOfName":["Chris","David"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabc6ef4dcbee04fbbc17") } > db.demo542.insertOne({"ListOfName":null});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabc8ef4dcbee04fbbc18") } > db.demo542.insertOne({"ListOfName":["David"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabd3ef4dcbee04fbbc19") } > db.demo542.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabdaef4dcbee04fbbc1a") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo542.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8cabc6ef4dcbee04fbbc17"), "ListOfName" : [ "Chris", "David" ] } { "_id" : ObjectId("5e8cabc8ef4dcbee04fbbc18"), "ListOfName" : null } { "_id" : ObjectId("5e8cabd3ef4dcbee04fbbc19"), "ListOfName" : [ "David" ] } { "_id" : ObjectId("5e8cabdaef4dcbee04fbbc1a"), "Name" : "John" }
以下是查询以检查特定值-
> var id = "David"; > db.demo542.aggregate([ ... { ... "$project": { ... "matched": { ... "$eq": [ ... { ... "$size": { ... "$ifNull": [ ... { "$setIntersection": [ "$ListOfName", [id] ] }, ... [] ... ] ... } ... }, ... 1 ... ] ... } ... } ... } ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e8cabc6ef4dcbee04fbbc17"), "matched" : true } { "_id" : ObjectId("5e8cabc8ef4dcbee04fbbc18"), "matched" : false } { "_id" : ObjectId("5e8cabd3ef4dcbee04fbbc19"), "matched" : true } { "_id" : ObjectId("5e8cabdaef4dcbee04fbbc1a"), "matched" : false }