所以我有一个集合,它的属性是一个array.假设房产被命名为买家.最初,买方数组中存储的对象如下所示

buyers: [
{
   userId: "1234",
   Prop1: "AAaaa" 
},
{
   userId: "2312",
   Prop1: "Abba" 
},
]

一段时间后,我们向模式中添加了一个属性(Quantity).但旧数据仍然只包含这两个属性.

不,我需要查询数据并对该新属性‘Quantity’求和,其规则是,如果该属性缺失,它实际上应该是1,这是该值的替换值.

我try 使用$ifull&和,但它并不是 for each 缺少Quantity属性的买家加1.

这就是我所拥有的.

$addFields: {
      sumBought: {
        $sum: {
          $ifNull: ["$buyers.quantity", 1],
        },
      },
    },

推荐答案

您可以使用$map将数组转换为值数组,方法是将1添加到映射数组$ifNull,然后取映射数组的$sum

db.collection.aggregate([
  {
    $addFields: {
      sumBought: {
        $sum: {
          $map: {
            input: "$buyers",
            in: { $ifNull: [ "$$this.quantity", 1 ] }
          }
        }
      }
    }
  }
])

playground

或者,您也可以使用$reduce

db.collection.aggregate([
  {
    $addFields: {
      sumBought: {
        $reduce: {
          input: "$buyers",
          initialValue: 0,
          in: { $add: [ "$$value", { $ifNull: [ "$$this.quantity", 1 ] } ] }
        }
      }
    }
  }
])

playground

Mongodb相关问答推荐

GO:如何在MongoDB中区分空字符串和nil

如何根据两个 struct 创建一个Mongo文档?

数组中字符串的Mongo查询集合和推送到新数组嵌套对象

如何在Mongo中查找数组中的特定对象

为什么 mongoose 在 mongodb 中找不到我的数据

MongoDB - 使用许多嵌套对象更新嵌套数组

聚合 $accumulator + $project

mongo:在 mongodb 6.0 docker 容器上找不到命令

mongoDB 过滤、排序和排名结果

findOneAndUpdate 和 findOneAndReplace 有什么区别?

在 Mongoose 中清理用户输入

Mongodb插入没有_id字段的文档

Select 匹配mongodb中两个字段的concat值的记录

如何使用 mongoexport 导出排序数据?

mongodb nodejs - 转换圆形 struct

Mongodb:为什么 show dbs 不显示我的数据库?

如何在 NoSql 数据库(MongoDB)中强制执行外键?

MongoDB 中的多个 $inc 更新

多次使用位置 `$` 运算符来更新嵌套数组

哪个数据库适合我的应用程序 mysql 或 mongodb ?使用 Node.js 、 Backbone 、 Now.js