Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Truy vấn MongoDB chọn trường này nếu trường kia null, ngược lại chọn trường đầu

Sử dụng toán tử $ifNull trong Aggregation Framework.

Tạo collection với document:

> db.querySelectDemo.insertOne({"Value1":10,"Value2":null});
{ "acknowledged" : true, "insertedId" : ObjectId("5cefc0ceef71edecf6a1f6b6") }
> db.querySelectDemo.insertOne({"Value1":null,"Value2":30});
{ "acknowledged" : true, "insertedId" : ObjectId("5cefc0d7ef71edecf6a1f6b7") }
> db.querySelectDemo.insertOne({"Value1":60,"Value2":40});
{ "acknowledged" : true, "insertedId" : ObjectId("5cefc0e2ef71edecf6a1f6b8") }

Hiển thị tất cả document:

> db.querySelectDemo.find().pretty();

Kết quả

{ "_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"), "Value1" : 10, "Value2" : null }
{ "_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"), "Value1" : null, "Value2" : 30 }
{ "_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"), "Value1" : 60, "Value2" : 40 }

Truy vấn Aggregation: nếu Value1 null thì lấy Value2, ngược lại lấy Value1:

> db.querySelectDemo.aggregate([
    {
      $project: {
        "Value1": { "$ifNull": [ "$Value1", "$Value2" ] }
      }
    }
]);

Kết quả

{ "_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"), "Value1" : 10 }
{ "_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"), "Value1" : 30 }
{ "_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"), "Value1" : 60 }