Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a for loop in the mongodb shell?

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!

like image 895
albert Avatar asked Sep 21 '16 15:09

albert


2 Answers

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.

like image 108
Rahul Kumar Avatar answered Nov 03 '22 09:11

Rahul Kumar


Insert many item at once.

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

To check

db.collectionName.find();
like image 34
Ahmad Sharif Avatar answered Nov 03 '22 08:11

Ahmad Sharif