【问题标题】:MongoDB cannot call method 'aggregate' of undefinedMongoDB 无法调用未定义的方法“聚合”
【发布时间】:2014-02-04 04:00:46
【问题描述】:

我正在尝试获取数组中的最低分数。我的错误是无法调用未定义的方法“聚合”。聚合方法是在mongodb中定义的,我什至找到了,db.students肯定是定义的。我似乎找不到哪里出错了。

var MongoClient = require('mongodb').MongoClient // Driver for connecting to MongoDB

MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
      if(err) throw err;

x = db.students.aggregate( [{ "$unwind":"$scores" },{"$match":{"scores.type":"homework"}},{ "$group":{"_id":"$_id","minscore":{"$min":"$scores.score" }}} ] )

x.result.forEach(function(doc) {
   db.students.update( { "_id": doc._id }, 
                       { "$pull": { "scores" : { 
                                          "score":doc.minscore, 
                                          "type":"homework"
                       } } } 
   );
});

});

我有一种感觉,我盯着这个看太久了,我有一种狭隘的感觉,感谢你用全新的眼光为我看它。

【问题讨论】:

  • db.students 不是有效对象。您需要通过 db.collection('students').aggregate(...) 访问该集合

标签: node.js mongodb aggregation-framework


【解决方案1】:

如果您要使用节点驱动程序,则不能使用与在 Mongo shell 中相同的语法。应该是这样的:

db.collection('students').aggregate();

Here's the reference.

【讨论】:

  • 哇,这是一个非常简洁、传递良好的答案,并且在深入了解之后才有意义。最重要的是,你这么快就回答了这个问题。谢谢。
  • 很高兴它有帮助!此外,如果您只是使用 js 文件来执行更复杂的 Mongo 操作,您可以直接在 Mongo shell 中运行它们,您不会使用 Node 驱动程序,并且会完全按照您在 shell 中的方式编写请求,或者从 shell 或从命令行启动 shell 时。 docs.mongodb.org/manual/tutorial/…
猜你喜欢
  • 2015-01-21
  • 2019-09-24
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多