【问题标题】:Unable to use aggregate function in MongoDB无法在 MongoDB 中使用聚合函数
【发布时间】:2020-01-03 09:10:50
【问题描述】:

MongoDB中的find函数之后可以使用聚合函数吗?我想查询一个文档,然后根据查找结果进行聚合。

db.movies.find({"runtime":30},{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}).limit(3).aggregate([{$group:{_id:"$runtime",award_wins:{$sum:1}}}])

执行此命令后,我收到一个错误,聚合不是函数,

E QUERY [js] TypeError: db.movies.find(...).limit(...).aggregate is not a function :

【问题讨论】:

    标签: database mongodb nosql mongodb-query aggregate


    【解决方案1】:

    aggregate() 不能与find() 一起使用。您应该使用相应的聚合方法来执行查询。

    编辑: 试试这个。

    db.movies.aggregate([
    {$match:{"runtime":30}},
    {$project:{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}},
    {$limit:3},
    {$group:{_id:"$runtime",award_wins:{$sum:1}}}
    ])
    

    【讨论】:

    • 你能用一个例子解释一下吗?
    【解决方案2】:

    如下运行,你不能在 find 之后运行聚合

    db.movies.aggregate([
    {$match:{"runtime":30}},
    {$project{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}},
    {$limit:3},
    {$group:{_id:"$runtime",award_wins:{$sum:1}}}
    ])
    

    【讨论】:

    • 如果答案有帮助,请点赞并标记为答案。
    【解决方案3】:

    要调用聚合函数,您必须使用 db..aggregate 而不是 find。试试下面的:

    db.movies.aggregate({"runtime":30},{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}).limit(3).aggregate([{$group:{_id:"$runtime",award_wins:{$sum:1}}}])
    

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2021-03-10
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      相关资源
      最近更新 更多