How to use a for loop in the mongodb shell?

albert picture albert · Sep 21, 2016 · Viewed 30.2k times · Source

How can i use a for loop in the mongo db shell?

My attemps are stucking at this point:

for (var i = 0; i <= 6; i=i+0.12){
var n = i + 0.12;
db.test.aggregate(
    { $sort: {'deviation': -1}},
    { $unwind: '$foo' },
    { $match: { 'foo.km': {$gt: {n}, $lt: {i}}}},
    { $limit: 1}
)
}

Thanks for help!

Answer

Rahul Kumar picture Rahul Kumar · Sep 21, 2016

MongoDB shell uses javascript engine and I remember in javascript some year ago some problem with using var keyword inside loop as we use int inside java.

try by removing var from loop statement

for (i = 0; i <= 6; i=i+0.12){ 
  var n = i + 0.12;
 db.test.aggregate([
  { $sort: {'deviation': -1}},
  { $unwind: '$foo' },
  { $match: { 'foo.km': {$gt: {n}, $lt: {i}}}},
  { $limit: 1}
 ])
}

Also be mindful that js is asynchronous by default, so it might not wait for aggregate to complete and might move to next iteration.