1

我想使用 mongodb 来实现类似 mysql "select ab from table" 的简单查询,但是聚合框架查询结果不正确。

数据:

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

mongodb命令:

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

1 回答 1

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 版本吗?

于 2013-02-07T08:39:51.600 回答