mongodb - 使用 mongodb 中的条件将字段添加到集合

我想将一个新的 bool 字段添加到包含其他字段信息的集合中。

我的样本数据是;

{ 
    "_id" : ObjectId("50abae61edecb53c740022eb"), 
    "pull_request" : {
        "diff_url" : null, 
        "patch_url" : null, 
        "html_url" : null
    }
}
{ 
    "_id" : ObjectId("50abae61edecb53c740022ec"), 
    "pull_request" : {
        "diff_url" : "https://github.com/joyent/http-parser/pull/106.diff", 
        "patch_url" : "https://github.com/joyent/http-parser/pull/106.patch", 
        "html_url" : "https://github.com/joyent/http-parser/pull/106"
    }, 
} 

新字段是“hasPullRequest”;如果 pull_request 字段为 null,则 hasPullRequest:false;否则 hasPullRequest:true。我的意思是在下面;

{ 
    "_id" : ObjectId("50abae61edecb53c740022eb"), 
    "pull_request" : {
        "diff_url" : null, 
        "patch_url" : null, 
        "html_url" : null
    },
    "hasPullRequest" : false
}
{ 
    "_id" : ObjectId("50abae61edecb53c740022ec"), 
    "pull_request" : {
        "diff_url" : "https://github.com/joyent/http-parser/pull/106.diff", 
        "patch_url" : "https://github.com/joyent/http-parser/pull/106.patch", 
        "html_url" : "https://github.com/joyent/http-parser/pull/106"
    }, 
    "hasPullRequest" : true
} 

我试过这个查询,但它没有运行;

db.getCollection('issues').aggregate([
   {
     $addFields: {
       hasPullRequest:  { 
            "$cond": {
            if: { { "$eq": {"$pull_request": null}} ,
            then: false,
            else: true
            } 
      }
   }
])

我该怎么做?

最佳答案

因为有些记录没有pull_request字段,我加了一个or条件;

    db.getCollection("test").aggregate( [ 
  { 
      $addFields: { 
          hasPullRequest: { 
             $cond: [ 
                 { 
                     $or:
                     [ 
                         { $and: [ 
                            { $eq: [ "$pull_request.diff_url", null ] },
                            { $eq: [ "$pull_request.patch_url", null ] },
                            { $eq: [ "$pull_request.html_url", null ] },
                                 ]
                         },
                         {  $eq:[{ $ifNull: [ "$pull_request", 0 ] },0]  }
                      ]
                  },
                 false, 
                 true 
             ] 
          } 
      } 
  },
  {
        $out: "Issues2"
  }
]
).pretty()

它非常适合我。

https://stackoverflow.com/questions/60169873/

相关文章:

oracle - 在 Apex 中提交表单之前添加确认

list - 得到 "Fatal error: Index out of range": show

typescript - typescript 中的 bool 列表是否有 "all"或 "any"

python - 如何在 XGBoost 库的 plot_tree 函数中包含特征名称?

powershell - Terraform azurerm_virtual_machine_ext

r - 确定一周中的某一天是否是 R 中每月的第 2/3 等星期一/星期二/等

google-cloud-platform - 共享 VPC 和 VPC 对等组合

ios - 从 XCode 的调试导航器中清除崩溃日志

bash - 如何在 bash 中循环遍历 jq 唯一数组?

node.js - Firebase 函数错误 : The default Firebase app