如何将 $ifNull 与 MongoDB 聚合一起使用?
$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" }
广告