如何在 mongodb shell 中使用 for 循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39620167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:49:42  来源:igfitidea点击:

How to use a for loop in the mongodb shell?

mongodbmongodb-queryaggregation-frameworkmongo-shellmongodb-aggregation

提问by albert

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

如何在 mongo db shell 中使用 for 循环?

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!

感谢帮助!

回答by Rahul Kumar

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.

MongoDB shell 使用 javascript 引擎,我记得一年前在 javascript 中使用 var 关键字在循环中出现了一些问题,因为我们在 java 中使用 int。

try by removing var from loop statement

尝试从循环语句中删除 var

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.

还要注意 js 默认是异步的,所以它可能不会等待聚合完成而可能会移动到下一次迭代。

回答by albert

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}
 )
}

回答by Arpit

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

第二件事是这里 n 大于 i。然后匹配查询应该像 foo.km < n 和 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}
    )
}

回答by Ahmad Sharif

Insert many item at once.

一次插入多个项目。

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

To check

去检查

db.collectionName.find();

回答by Siraj Hussain

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

你的循环是错误的,它应该 <=6。像这样

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