首页 > 解决方案 > 如何在 mongodb redact 中解决此聚合问题

问题描述

我在 mongodb 中有人员数据集,我想在其中获取所有朋友的 id 大于 1 的人。我尝试使用 $redact 聚合管道,但它不起作用。这是样本数据

{
"_id" : "5d7a16904d08c0c435e4255b",  
"name" : {
    "first" : "Roberta",
    "last" : "Jackson"
},
"company" : "YURTURE",
"email" : "roberta.jackson@yurture.io",
"age":26,
"registered" : "Sunday, May 5, 2019 2:44 PM",
"latitude" : "36.56389",
"longitude" : "-72.518115",
"friends" : [ 
    {
        "id" : 0,
        "name" : "Vicki Peck"
    }, 
    {
        "id" : 1,
        "name" : "Jeanie Boyd"
    }, 
    {
        "id" : 2,
        "name" : "Terra Curtis"
    }
],

}

我尝试使用聚合管道编辑,但我没有在朋友列表中获得任何数据。

db.getCollection('test_redact').aggregate([  {    $project:{        
"name" : 1,
      "friends" : 1,
      "greeting" : 1,
      }},
       {
           $redact:{
               $cond: {
                    if: { $gte: [ "$friends.id", 1 ] },                           
                   then: "$$DESCEND",
                   else: "$$PRUNE"
                   }
                   }
           }
])

这是我在执行聚合后得到的示例输出 { "_id" : "5d7a16904d08c0c435e4255b", "age" : 26, "friends" : [], "greeting" : "Hello, Roberta! You have 9 unread messages." }

标签: mongodbshellmongodb-querypipelineaggregation

解决方案


以下查询可以为我们提供预期的输出:

db.getCollection("collection").find({"friends.id":{$gte:1}},{"name":1,"friends":1,"greeting":1}).pretty()

只获取那些 id 大于 1 的朋友:

db.getCollection("collection").aggregate([
  {
    $match:{
      "friends.id":{
        $gte:1
      }
    }
  },
  {
    $project:{
      "name":1,
      "friends":{
        $filter:{
          "input":"$friends",
          "as":"friend",
          "cond":{
            $gte:["$$friend.id",1]
          }
        }
      },
      "greeting":1
    }
  }
]).pretty()

使用 $redact:

db.getCollection("collection").aggregate([
  {
    $redact:{
      $cond:[
        {
          $or:[
            {
              $gte:["$id",1]    
            },
            {
              $eq:["$id",undefined]
            }
          ]
        },
        "$$DESCEND",
        "$$PRUNE"
      ]
    }
  },
  {
    $project:{
      "name":1,
      "friends":1,
      "greeting":1
    }
  }
]).pretty()

推荐阅读