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!
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.