首页 文章

MongoDB:聚合框架:字段之间的$ match

提问于
浏览
18

我有一个包含两个文档的测试集合:

> db.test.find().pretty()
{ "_id" : ObjectId("510114b46c1a3a0f6e5dd7aa"), "a" : 1, "b" : 2 }
{ "_id" : ObjectId("510114c86c1a3a0f6e5dd7ab"), "a" : 3, "b" : 1 }

使用聚合框架,我想只获取a大于b的文档 . $ gt只获取参数中的值而不是字段...

> db.test.aggregate([{"$match":{"$a":{"$gt":"$b"}}}])
{ "result" : [ ], "ok" : 1 } /* don't work*/

你有什么想法吗?

提前致谢

最好的祝福

1 回答

  • 37

    嗯我没有太多测试我会说你可以使用 $cmp

    http://docs.mongodb.org/manual/reference/aggregation/cmp/#_S_cmp

    db.test.aggregate([
        {$project: {
            // All your other fields here
            cmp_value: {$cmp: ['$a', '$b']}
        }},
        {$match: {cmp_value: {$gt: 0}}} 
    ])
    

    可能有更好的方法,但我没有在我附近安装MongoDB进行测试 .

相关问题