MongoDB聚合框架$减

时间:2013-02-07 06:07:39

标签: mongodb aggregation-framework

我想用mongodb来实现简单的查询,比如mysql“select a-b from table”,但聚合框架查询结果不对。

数据:

{ "_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 个答案:

答案 0 :(得分:2)

我无法复制你的行为:

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

您可以向我们提供一些类似MongoDB版本的信息吗?