1

My mongo data as follows.

{
"date" : Jan,
"rank" : 1,
"StudentId: 10
},
{
"date" : Jan,
"rank" : 1,
"StudentId: 20
},
{
"date" : Jan,
"rank" : 2,
"StudentId: 30
},

{
"date" : Feb,
"rank" : 1,
"StudentId: 10
},
{
"date" : Feb,
"rank" : 2,
"StudentId: 20
},
{
"date" : Feb,
"rank" : 3,
"StudentId: 30
}

I would like to get the desired result as the moved ranks from 1 to 2 with month movement from Jan to Feb. ie. From the above json I want the below result

{
"date" : Feb,
"rank" : 2,
"StudentId: 20
}

ie.. The from date is Jan, to date is Feb, from date rank is 1 and to date rank is 2.

How can I achieve this using the mongo db query???

Alex
  • 790
  • 1
  • 7
  • 22

1 Answers1

0

You can use the range and cond aggregate operators to achieve this:

db.ranks.aggregate(
   [
      {
         $project:
           {
             item: 1,
             date:
               {
                 $cond: [ your condition here]
               },
         rank: {$range:[0, 1]}
           }
      }
   ]
)

should work!

vaibhav
  • 3,929
  • 8
  • 45
  • 81
  • Thank you for your valuable reply.the condition is seems like a 'case when' statement in mysql. when lowerlimit.date= 'jan' and lowerlimit.rank = 1, then upperlimit.date = 'feb' and upperlimit.rank = 2 and upperlimit.StudentId=lowerlimit.StudentId. Is this possible to write in mongo? – Alex Feb 06 '18 at 11:07
  • Mongo would not allow nesting queries per se.. the collection design should be such that we can query based on the requirements or available operators either as criterias or aggregates. At most you can do is define a function i.e. and javascript function which returns the intended result. but that again i m unsure is a good idea.. – vaibhav Feb 06 '18 at 11:47
  • https://stackoverflow.com/questions/9883617/how-to-make-nested-queries-in-mongodb-that-works-like-nested-sql-select-queries – vaibhav Feb 06 '18 at 11:53