MongoDB aggregate() - error “TypeError: Cannot cal

2019-07-31 17:12发布

问题:

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