$multiply(聚合)
定义
例子
请考虑包含以下文档的 sales
集合:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity": 2, date: ISODate("2014-03-01T08:00:00Z") } { "_id" : 2, "item" : "jkl", "price" : 20, "quantity": 1, date: ISODate("2014-03-01T09:00:00Z") } { "_id" : 3, "item" : "xyz", "price" : 5, "quantity": 10, date: ISODate("2014-03-15T09:00:00Z") }
下面的聚合使用 $project
管道中的 $multiply
表达式来乘以 price
和 quantity
字段:
db.sales.aggregate( [ { $project: { date: 1, item: 1, total: { $multiply: [ "$price", "$quantity" ] } } } ] )
操作返回以下结果:
{ "_id" : 1, "item" : "abc", "date" : ISODate("2014-03-01T08:00:00Z"), "total" : 20 } { "_id" : 2, "item" : "jkl", "date" : ISODate("2014-03-01T09:00:00Z"), "total" : 20 } { "_id" : 3, "item" : "xyz", "date" : ISODate("2014-03-15T09:00:00Z"), "total" : 50 }