如何在MongoDB聚合中使用$ ifNull?
$ifNull计算一个表达式,如果该表达式计算为非null值,则返回该表达式的值。
首先让我们创建一个包含文档的集合-
> db.demo372.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e591aea2ae06a1609a00af6") } > db.demo372.insertOne({"FirstName":null}); { "acknowledged" : true, "insertedId" : ObjectId("5e591aef2ae06a1609a00af7") } > db.demo372.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e591af42ae06a1609a00af8") } > db.demo372.insertOne({"FirstName":null}); { "acknowledged" : true, "insertedId" : ObjectId("5e591afb2ae06a1609a00af9") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo372.find();
这将产生以下输出-
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" } { "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : null } { "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" } { "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : null }
以下是将$ifNull与聚合一起使用的查询-
> db.demo372.aggregate( ... [ ... { ... $project: { ... ... FirstName: { $ifNull: [ "$FirstName", "NOT PROVIDED" ] } ... } ... } ... ] ... )
这将产生以下输出-
{ "_id" : ObjectId("5e591aea2ae06a1609a00af6"), "FirstName" : "Chris" } { "_id" : ObjectId("5e591aef2ae06a1609a00af7"), "FirstName" : "NOT PROVIDED" } { "_id" : ObjectId("5e591af42ae06a1609a00af8"), "FirstName" : "David" } { "_id" : ObjectId("5e591afb2ae06a1609a00af9"), "FirstName" : "NOT PROVIDED" }