Mongoose:使用 $sum 更新插入文档

Mongoose: Upsert document with $sum

假设我有一个如下所示的文档:

var TestSchema = new Schema({
    _id: String,
    userId: Number,
    date: Date,
    usage: Object
});

当我向数据库中插入内容时,该文档可能如下所示:

{
    userId: 10,
    date: 2015-11-12,
    usage: {
        foo: 12,
        bar: 5
    }
}

现在是否可以更新此文档,其中 usage 使用新文档和旧文档的 $sum?

所以当我做findOneAndUpdate的时候,我基本上只想把用法加起来。

$sum operator is applicable only to the aggregation framework via the $group operator pipeline stage and can only return a sum on each grouped field (not multiple fields). What you need is the $add arithmetic operator and the specific operation you want can't be done with an atomic update, you'd need two operations to do this: an aggregation which adds up the old field with the new object and then the findOneAndUpdate操作。

考虑以下最终会产生所需更新的操作:

var newUsageObj = {
    "foo": 8,
    "bar": 15
},
query = { "userId": 10 };

// Using the mongoose aggregation builder
Model.aggregate()
     .match(query)
     .project({
         "updatedUsage": {
             "foo": { "$add": [ "$usage.foo", newUsageObj.foo ]},
             "bar": { "$add": [ "$usage.bar", newUsageObj.bar ]}
         })
     .exec(function (err, res){
         if (err) return handleError(err);
         res.forEach(function (doc){
             Model.findOneAndUpdate(query, { "usage": doc.updatedUsage }, options, callback);
         });
     });

阅读 Aggregation 文档了解更多信息。