mongoDB 聚合aggregate (一)

通常我们需要按照一定的规则查询数据库,但是常常需要对数据里面的进行统计,归类什么的。
这时候就需要用到mongo 聚合了;
mongoose $subtract

  • Subtract Numbers
{
    "_id": 1,
    "item": "abc",
    "price": 10,
    "fee": 2,
    "discount": 5,
    "date": ISODate("2014-03-01T08:00:00Z")
} {
    "_id": 2,
    "item": "jkl",
    "price": 20,
    "fee": 1,
    "discount": 2,
    "date": ISODate("2014-03-01T09:00:00Z")
}
db.sales.aggregate([{
    $project: {
        item: 1,
        total: {
            $subtract: [{
                $add: ["$price", "$fee"]
            }, "$discount"]
        }
    }
}])

result:

{ "_id" : 1, "item" : "abc", "total" : 7 }
{ "_id" : 2, "item" : "jkl", "total" : 19 }
  • Subtract Two Dates
db.sales.aggregate([{
    $project: {
        item: 1,
        dateDifference: {
            $subtract: [new Date(), "$date"]
        }
    }
}])

result:

{ "_id" : 1, "item" : "abc", "dateDifference" : NumberLong("11713985194") }
{ "_id" : 2, "item" : "jkl", "dateDifference" : NumberLong("11710385194") }

你可能感兴趣的:(mongoDB 聚合aggregate (一))