小编Roh*_*ala的帖子

用于算术运算的MongoDB聚合 - 子文档字段

我们有一个聚合查询,可以预测几个子文档.我们想在这些预测值上应用Sum和Product等几个算术运算.

聚合查询 -

Item.aggregate([
        { $unwind: '$dummy'},       
        { $match: {'dummy.storage': {$gt: 0}} },
        { $group: {_id: '$_id',
                    dummy: {$push: '$dummy'},
                    original_y: { $first: "$original_y" },
                    new_y: { $first: "$new_y" },

        }},
        {$project:{
                  original_y: 1, new_y: 1,
                  tallyAmount: {$sum: ["$new_y","$original_y"] }
                }
        },
     ]
    )
    .exec(function(err, results){   
        if(err)
        {
            console.log("Error : " + err);
            return res.json ({error: "Error"});

        }
        else if(!(results) || results == null || results.length == 0)
        {
            console.log("No Results Found");
            return res.json ({error: "No Results Today"});

        }else{

            res.send(results); …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js aggregation-framework

7
推荐指数
1
解决办法
892
查看次数

MongoDB聚合中的Mongoose虚拟

我的猫鼬模式如下:

var DSchema = new mongoose.Schema({
  original_y: {type: Number},,
  new_y: {type: Number},,
  date: {type: Date},
  dummy: [dummyEmbeddedDocuments]
  }, toObject: { virtuals: true }, toJSON: { virtuals: true}
});

DSchema.virtual('dateformatted').get(function () {
 return moment(this.date).format('YYYY-MM-DD HH:mm:ss');
});

module.exports = mongoose.model('D', DSchema);
Run Code Online (Sandbox Code Playgroud)

我的架构中的文档如下:

{
 id:1,
 original_y: 200,
 new_y: 140,
 date: 2015-05-03 00:00:00.000-18:30,
 dummy: [
  {id:1, storage:2, cost: 10},
  {id:2, storage:0, cost: 20},
  {id:3, storage:5, cost: 30},
  ]
}
Run Code Online (Sandbox Code Playgroud)

我的查询:

Item.aggregate([
{ 
    "$match": {
        "dummy.storage": {"$gt": 0}
    } 
},
{ 
    "$unwind": "$dummy"
},
{ …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js aggregation-framework

6
推荐指数
2
解决办法
3232
查看次数