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
The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.
The $match stage of the pipeline can be used to filter documents so that only ones meeting certain criteria move on to the next stage. In this article, we'll discuss the $match stage in more detail and provide examples that illustrate how to perform match aggregation in MongoDB.
Each stage of the aggregation pipeline transforms the document as the documents pass through it. However, once an input document passes through a stage, it doesn't necessarily produce one output document. Some stages may generate more than one document as an output. MongoDB provides the db.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With