在 MongoDB aggregate 中使用 $redact?


$redact 根據儲存在文件本身中的資訊限制文件的內容。您可以在聚合中將 $cond 與 $redact 一起使用。讓我們建立一個包含文件的集合 −

> 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")
}

使用 find() 方法顯示集合中的所有文件 −

> db.demo546.find();

這將產生以下輸出 −

{ "_id" : ObjectId("5e8e263f9e5f92834d7f05d7"), "Value1" : 10, "Value2" : 20 }
{ "_id" : ObjectId("5e8e26549e5f92834d7f05d8"), "Value1" : 40, "Value2" : 30, "Value3" : 50 }
{ "_id" : ObjectId("5e8e26619e5f92834d7f05d9"), "Value1" : 100, "Value2" : 200, "Value3" : null }
{ "_id" : ObjectId("5e8e26e09e5f92834d7f05da"), "Value1" : 400, "Value2" : 1000, "Value3" : null }
{ "_id" : ObjectId("5e8e26f59e5f92834d7f05db"), "Value1" : 400, "Value2" : 200, "Value3" : null }
{ "_id" : ObjectId("5e8e27159e5f92834d7f05dc"), "Value1" : 400, "Value2" : 1000, "Value3" : 60 }

以下是帶有 MongoDB 聚合的 $exists 和 $redact 的查詢 −

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

這將產生以下輸出 −

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

更新時間: 14-May-2020

550 次瀏覽

開啟你的事業

完成學習,即可獲得證書

開始
廣告
© . All rights reserved.