MongoDB aggregate() - error “TypeError: Cannot call method 'forEach' of undefined”

假装没事ソ 提交于 2019-12-11 10:45:33

问题


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

In file "out.txt" I have the error

TypeError: Cannot call method 'forEach' of undefined at script.js

The same problem, when I run the script from mongo shell mongo.exe (by using load()).

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 version 2.6.5


回答1:


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


来源:https://stackoverflow.com/questions/27095122/mongodb-aggregate-error-typeerror-cannot-call-method-foreach-of-undefine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!