为此,请使用$ifNull运算符
首先让我们创建一个包含文档的集合-
> dbquerySelectDemoinsertOne({"Value1":10,"Value2":null}); { "acknowledged" : true, "insertedId" : ObjectId("5cefc0ceef71edecf6a1f6b6") } > dbquerySelectDemoinsertOne({"Value1":null,"Value2":30}); { "acknowledged" : true, "insertedId" : ObjectId("5cefc0d7ef71edecf6a1f6b7") } > dbquerySelectDemoinsertOne({"Value1":60,"Value2":40}); { "acknowledged" : true, "insertedId" : ObjectId("5cefc0e2ef71edecf6a1f6b8") }
在find()
方法的帮助下显示集合中的所有文档-
> dbquerySelectDemofind()pretty();
输出结果
{ "_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"), "Value1" : 10, "Value2" : null } { "_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"), "Value1" : null, "Value2" : 30 } { "_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"), "Value1" : 60, "Value2" : 40 }
以下是查询来选择一个字段(如果其他字段为空)-
> dbquerySelectDemoaggregate([ { $project: { "Value1": { "$ifNull": [ "$Value1", "$Value2" ] } } } ]);
输出结果
{ "_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"), "Value1" : 10 } { "_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"), "Value1" : 30 } { "_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"), "Value1" : 60 }