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

Triển khai $cond trong MongoDB projection dựa trên sự hiện diện/vắng mặt của trường

Sử dụng $cond kết hợp $anyElementTrue trong stage $project. Giá trị NULL (trường không tồn tại) hoặc mảng rỗng sẽ đánh giá thành FALSE.

Tạo collection với trường StudentName có giá trị null và chuỗi:

> db.presenceDemo.insertOne({"StudentName":null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f70c25ddae1f53b621f3") }
> db.presenceDemo.insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f71425ddae1f53b621f4") }
> db.presenceDemo.insertOne({"StudentName":null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f71825ddae1f53b621f5") }
> db.presenceDemo.insertOne({"StudentName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f71e25ddae1f53b621f6") }

Hiển thị dữ liệu (2 bản ghi null, 2 bản ghi có tên):

> db.presenceDemo.find();
{ "_id" : ObjectId("5e06f70c25ddae1f53b621f3"), "StudentName" : null }
{ "_id" : ObjectId("5e06f71425ddae1f53b621f4"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e06f71825ddae1f53b621f5"), "StudentName" : null }
{ "_id" : ObjectId("5e06f71e25ddae1f53b621f6"), "StudentName" : "David" }

Aggregation với $cond: nếu $anyElementTrue của [$StudentName] thì trả 1, ngược lại 0:

> db.presenceDemo.aggregate([
...   { "$project": {
...     "MyValue": {
...       "$cond": [
...         { "$anyElementTrue": [ [ "$StudentName" ] ] },
...         1,
...         0
...       ]
...     }
...   }}
...]);

Kết quả: null → 0, có giá trị → 1:

{ "_id" : ObjectId("5e06f70c25ddae1f53b621f3"), "MyValue" : 0 }
{ "_id" : ObjectId("5e06f71425ddae1f53b621f4"), "MyValue" : 1 }
{ "_id" : ObjectId("5e06f71825ddae1f53b621f5"), "MyValue" : 0 }
{ "_id" : ObjectId("5e06f71e25ddae1f53b621f6"), "MyValue" : 1 }