MongoDB aggregation framework $subtract

北战南征 提交于 2019-12-23 05:39:15

问题


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
        },
]

回答1:


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?



来源:https://stackoverflow.com/questions/14744706/mongodb-aggregation-framework-subtract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!