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

Sử dụng $redact trong MongoDB aggregate

Toán tử $redact giới hạn nội dung tài liệu dựa trên thông tin lưu trữ trong chính tài liệu đó. Có thể kết hợp $cond với $redact trong pipeline aggregate.

Tạo collection với các tài liệu có trường Value3 có thể null:

> db.demo546.insertOne({"Value1":10,"Value2":20});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8e263f9e5f92834d7f05d7") }
> db.demo546.insertOne({"Value1":40,"Value2":30,Value3:50});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8e26549e5f92834d7f05d8") }
> db.demo546.insertOne({"Value1":100,"Value2":200,Value3:null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8e26619e5f92834d7f05d9") }
> db.demo546.insertOne({"Value1":400,"Value2":1000,Value3:null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8e26e09e5f92834d7f05da") }
> db.demo546.insertOne({"Value1":400,"Value2":200,Value3:null});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8e26f59e5f92834d7f05db") }
> db.demo546.insertOne({"Value1":400,"Value2":1000,Value3:60});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8e27159e5f92834d7f05dc") }

Hiển thị tất cả:

> db.demo546.find();

Truy vấn $redact giữ lại tài liệu thỏa mãn: Value1 < Value2 VÀ Value3 không null:

> db.demo546.aggregate( { "$redact": { "$cond": { "if": { "$and": [ { "$lt": [ "$Value1", "$Value2" ] }, { "$ifNull": [ "$Value3", false ] } ] }, "then": "$$KEEP", "else": "$$PRUNE" } } } );

Kết quả (chỉ 1 tài liệu thỏa mãn):

{ "_id" : ObjectId("5e8e27159e5f92834d7f05dc"), "Value1" : 400, "Value2" : 1000, "Value3" : 60 }