【问题标题】:MongoDb aggregate addField if an array of object contains object with specific attribute如果对象数组包含具有特定属性的对象,则 MongoDb 聚合 addField
【发布时间】:2020-08-03 21:25:16
【问题描述】:

如果集合 (sales) 内的orders 数组包含一个具有status 属性值delivered 的对象,我需要使用addField 聚合查询添加一个completed 属性。

db.sales.insertMany([
    {
        "_id" : 1,
        "salesId" : "2938432",
        "customerId" : "987677789",
        "amount:"23000"
        "orders":[{
            orderId:"TX8383428979382",
            status:"cancelled"
        },
        {
            orderId:"TX8383428979383",
            status:"fullfilled"
        }]
    },
    {
        "_id" : 1,
        "salesId" : "2938433",
        "customerId" : "987676578",
        "amount:"13000"
        "orders":[
        {
            orderId:"TX838342892437363",
            status:"placed"
        }]
    },
    .........
)]

我的汇总查询

db.sales.aggregate([
  {$match:{....}},
  {$addFields:{
    completed: {
                 $cond: { if: { /* code to check if orders array contains an object with `status:fullfilled` }, then: true, else: false }
               }
  }},
])

如何检查对象数组中的属性是否匹配?

【问题讨论】:

  • 您可以将$map 聚合运算符与$addFields 阶段一起使用。 $map 将让您遍历 orders 数组,您可以检查数组的每个元素的条件并在匹配时添加新属性。
  • 谢谢@prasad_。似乎我也可以减少。但我无法把它写成代码。如果你能举个例子会很有帮助
  • 您想在哪里添加completed 属性?对于“订单”子文档根/顶级?

标签: arrays node.js mongodb mongodb-query


【解决方案1】:

这是使用$reduce 数组运算符添加新属性completed 的聚合,该属性基于orders.status“已交付”派生而来。

db.sales.aggregate( [
{
    $addFields: {
        completed: {
            $reduce: {
                input: "$orders", initialValue: false,
                in: {
                     $cond: [ { $eq: [ "$$this.status", "delivered" ] }, 
                                true, 
                                "$$value"
                     ]
                }
            }
        }
    }
}
] ).pretty()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-23
    • 2015-08-11
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多