MongoDB Aggregate()-错误"TypeError:无法调用未定义的方法'forEach'" [英] MongoDB aggregate() - error "TypeError: Cannot call method 'forEach' of undefined"
问题描述
我在"script.js"中有以下脚本:
I have the following scrip in "script.js"
conn = new Mongo();
db = conn.getDB("learn");
db.contracts.aggregate([
{ $match: { regionCode: '77' } },
{ $unwind: '$products' },
{
$project: {
_id: '$_id',
regNum: '$regNum',
prodName: '$products.name',
prodPrice: '$products.price'
}
},
{ $match: { 'prodName' : 'Water' } }
], {cursor:{}}).result.forEach(printjson);
我通过以下方式在命令提示符下运行它
I run it from the command prompt by the following way
mongo script.js >> out.txt
mongo script.js >> out.txt
在文件"out.txt"中出现错误
In file "out.txt" I have the error
TypeError:无法在script.js中调用未定义的方法'forEach'
TypeError: Cannot call method 'forEach' of undefined at script.js
当我从mongo shell mongo.exe(通过使用load())运行脚本时,同样的问题.
The same problem, when I run the script from mongo shell mongo.exe (by using load()).
当我从Robomongo 0.8.4运行相同的聚合命令时,我获得了成功的结果(3个json格式的文档).有人知道,为什么会发生这种情况?
When I run the same aggregate command from the Robomongo 0.8.4 I have succesive result (3 documents in json format). Does anybody know, why this may happen?
Mongodb版本2.6.5
Mongodb version 2.6.5
推荐答案
您需要在没有result
变量访问权限的情况下运行它.在shell
中访问时,mongodb返回的cursor
没有名为result
的属性,因此会出现错误.
You need to run it without the result
variable access. The cursor
returned by mongodb when accessed in the shell
, does not have a property named result
and hence you get the error.
db.contracts.aggregate([
{ $match: { regionCode: '77' } },
{ $unwind: '$products' },
{
$project: {
_id: '$_id',
regNum: '$regNum',
prodName: '$products.name',
prodPrice: '$products.price'
}
},
{ $match: { 'prodName' : 'Water' } }
], {cursor:{}}).forEach(printjson);
这篇关于MongoDB Aggregate()-错误"TypeError:无法调用未定义的方法'forEach'"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!