Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : aggregation framework : $match between fields

Tags:

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

like image 469
hotips Avatar asked Jan 24 '13 12:01

hotips


People also ask

What does $match do in MongoDB?

The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.

What can the $match aggregation stage be used for?

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.

What passes through a MongoDB aggregation pipeline?

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.


1 Answers

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.

like image 98
Sammaye Avatar answered Sep 28 '22 08:09

Sammaye