MongoDB : aggregation framework : $match between f

2019-01-09 06:18发布

问题:

I have a test collection with two documents :

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

With aggregation framework, I want to get only the documents where a is greater than b. $gt get only values in argument not fields...

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

Do you have some ideas ?

Thanks in advance

Best regards

回答1:

Hmm without much testing on my end I will say you can use $cmp for this:

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

There might be a better way but I haven't got a MongoDB installation near me to test.