Mongodb aggregation framework query

142 views
Skip to first unread message

juhi bhatia

unread,
Aug 16, 2012, 8:42:33 AM8/16/12
to mongod...@googlegroups.com, at...@entrib.com
I can do a mongodb aggregation query like:

db.elements.aggregate({$project : {"weekId" : 1, "monthId" : 1}}, {$match : {"weekId" : {$gt : 3*4}}})

the above query gives correct results.

I am trying to fire the query below:

db.elements.aggregate({$project : {"weekId" : 1, "monthId" : 1}}, {$match : {"weekId" : {$gt : "monthId" * 4}}})

the query evaluates w/o any errors, but does not give correct answer. I also tried "$monthId" instead of "monthId", I get the same results but incorrect.

My question is, can i do something like that in mongodb aggregation? If yes, what is the correct query mechanism?

Ross Lawley

unread,
Aug 16, 2012, 9:15:27 AM8/16/12
to mongod...@googlegroups.com, at...@entrib.com
Hi,

I don't think you can dynamically match in that way, but you dynamically test when doing your projection and match on those results.  So combining the $cond and  $multiply operators you can project a new field to match against.  See below:

db.elements.aggregate(
  {$project : {
    "weekId" : 1, 
    "monthId" : 1, 
    "test": { 
      $cond: [{$gt : ["$weekId", {$multiply: ["$monthId", 4]}]}, 1, 0 ]}
  }}, 
  {$match : { "test" : 1}},
  {$project : {
    "weekId" : 1, 
    "monthId" : 1,
  }}
)


Ross
Reply all
Reply to author
Forward
0 new messages