10

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!

albert
  • 163
  • 2
  • 3
  • 12

5 Answers5

6

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.

Rahul Kumar
  • 2,781
  • 1
  • 21
  • 29
  • still have this Error: Error: Line 6: Unexpected token } – albert Sep 22 '16 at 06:27
  • On a second look seems like aggregate argument should be inside array, I updated the answer. – Rahul Kumar Sep 22 '16 at 06:41
  • Rahul Kumar, please elaborate on what do you mean by JS being asynchronous by default. I highly doubt that. – E. Muuli Mar 26 '19 at 13:43
  • What I meant in simple term is that In JS it won’t wait for any I/O call to be completed and would jump on the next line of execution, that’s why we have callbacks in js. – Rahul Kumar Mar 26 '19 at 14:01
4

Insert many item at once.

for (var i = 1; i <= 25; i++) {
   db.collectionName.insert({ x : i })
}

To check

db.collectionName.find();
Ahmad Sharif
  • 4,141
  • 5
  • 37
  • 49
2

The code works like this but there are no results to show. At least not a syntax error anymmore

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}
 )
}
albert
  • 163
  • 2
  • 3
  • 12
2

I stuck on same error in past. We should use spaces/tabs in loop for every line with perfect coding style.

2nd thing is here n is greater than i. Then match query should like foo.km < n and foo.km > i

So, this is final code -

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': {$lt: {n}, $gt: {i}}}},
        { $limit: 1}
    )
}
Arpit
  • 1,423
  • 1
  • 17
  • 20
1

Your loop is wrong, It should be <=6. Like this

for (i = 0; i <= 6; i=i+0.12){
 //your logic
}
Siraj Hussain
  • 874
  • 9
  • 25