java mongo subtract,MongoDB聚合框架$ subtract

I'm want use mongodb to achieve simple query like mysql "select a-b from table", but aggregation framework query result is not right.

data:

{ "_id" : ObjectId("511223348a88785127a0d13f"), "a" : 1, "b" : 1, "name" : "xxxxx0" }

{ "_id" : ObjectId("511223348a88785127a0d13f"), "a" : 2, "b" : 2, "name" : "xxxxx1" }

mongodb cmd:

db.site.aggregate([

{ $match: {

"a" : {$exists:true},

"b" : {$exists:true},

}

},

{ $project: { _id : 0,name : 1,

r1: {$subtract:["$a", "$b"]} }

},

{ $limit: 100 },

]);

"result" : [

{

"name" : "xxxx1",

"r1" : -1

},

{

"name" : "xxxx0",

"r1" : -2

},

]

解决方案

I cannot replicate your behaviour:

> db.tg.find()

{ "_id" : ObjectId("511223348a88785127a0d13f"), "a" : 1, "b" : 1, "name" : "xxxxx0" }

> db.tg.aggregate([{ $match: { "a" : {$exists:true}, "b" : {$exists:true} } }, { $project: { _id : 0,name : 1, r1: {$subtract:["$a", "$b"]} }}, { $limit: 100 }])

{ "result" : [ { "name" : "xxxxx0", "r1" : 0 } ], "ok" : 1 }

Can you give us a little more info like your MongoDB version?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值