【问题标题】:Mongodb - aggregation of subdocument and update with the resultMongodb - 子文档的聚合并使用结果更新
【发布时间】:2015-04-05 17:54:21
【问题描述】:

我有以下问题。我在一个子文档中找到并总结了每个值。
它给出了以下[ { _id: 551fb140e4b04589d8997213, sumOfpeople: 342 } ]

我想把sumOfpeople 插入同一个房子(同一个req.params.house_id)

House.aggregate([
                    { $match: {
                        id: req.params.house_id
                    }},
                    { $unwind: '$people' }, // unwind creates a doc for every array element
                    { $group: { 
                        _id: '$_id',
                        sumOfpeople: { $sum: '$people.nr'}
                    }}
                ], function (err, result) {
                    if (err) {
                        console.log(err);
                        return;
                    }


                    console.log(result);
                });

这是我想要在聚合后插入结果的模型。

module.exports = mongoose.model('House', {

  id: String,
  people: [{
    id: String, 
    nr: Number 
  }],
  sumOfpeople: Number //this is the field that I want to update after the aggregation 

});

我尝试使用 $set : {sumOfpeople: { $sum: '$people.nr'}}。 是否可以在聚合中使用 $set ,或者如何解决?

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    在进行聚合时,MongoDB 无法将结果直接写入现有文档。

    你有两个选择:

    1. 在应用程序代码中检索结果,然后在第二个查询中更新文档。

    2. 使用$out 运算符,它将聚合结果写入新集合。此操作将删除结果集合中的所有文档并插入新文档。 (http://docs.mongodb.org/manual/reference/operator/aggregation/out/)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      相关资源
      最近更新 更多