Javascript 循环不';我不在MongoDB工作
我在Mongo数据库中为搜索字谜编写了脚本:Javascript 循环不';我不在MongoDB工作,javascript,mongodb,Javascript,Mongodb,我在Mongo数据库中为搜索字谜编写了脚本: print("Search anagrams"); var input = db.dbName.find(); var i = 0; input.forEach(function(word) { var j = 0; var alphabetical = word.name.split("").sort().join(""); input.forEach(function(worter) { if (i
print("Search anagrams");
var input = db.dbName.find();
var i = 0;
input.forEach(function(word) {
var j = 0;
var alphabetical = word.name.split("").sort().join("");
input.forEach(function(worter) {
if (i != j) {
if (alphabetical == worter.name.split("").sort().join("")) {
print(word.name + " : " + worter + " - " + i + ", " + j);
}
}
j++;
});
i++;
});
但是第一个循环不起作用。你知道为什么吗?db中的样本记录:
{ "_id" : ObjectId("5491d807dacc815b3043ae24"), "name" : "monki" }
返回光标。它不是数组。在游标上迭代两次(外循环和内循环),这可能是个问题。检查这是否有效
input.forEach(function(word) {
console.log(word);
}
是的,这项工作。你们知道如何修复它吗?你们只需要在光标上循环一次。在代码中,游标多次查询db。要排序,请检查:和:可能会在文档“排序的名称”中添加其他字段,并存储排序的名称(按字母顺序排列)。然后按排序的名称字段进行排序。它可能更快。您可以将光标转换为数组:
var input=db.dbName.find().toArray()代码>
input.forEach(function(word) {
console.log(word);
}