How to use for loop in mongodb shell?

How can I use the for loop in mongo db shell?

My attempts are stuck 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 the help!

+6
source share
5 answers

The MongoDB shell uses the javascript mechanism, and a few months ago I remember in javascript some problem using the var inner loop, since we use int inside java.

try removing var from the 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 remember that js is asynchronous by default, so it may not wait for the aggregate to complete and move on to the next iteration.

+3
source

, <= 6.

for (i = 0; i <= 6; i=i+0.12){
 //your logic
}
+1

, . , 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}
 )
}
+1
source

I made the same mistake in the past. We should use spaces / tabs in the loop for each line with the perfect coding style.

The second thing here is n is greater than i. Then the match request should look like foo.km <n and foo.km> i

So this is the 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}
    )
}
0
source

Insert multiple items at once.

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

Check

db.collectionName.find();
0
source

Source: https://habr.com/ru/post/1655348/


All Articles