【问题标题】:Mongodb - $sort - Pipeline stage specification object must contain exactly one fieldMongodb - $sort - 管道阶段规范对象必须包含一个字段
【发布时间】:2020-02-04 08:59:44
【问题描述】:

我正在 mongodb 中进行聚合,并从下面的代码中得到一个“管道阶段规范对象必须包含一个字段”

    db.HomeworkAggregate.aggregate([
    {
      $match:{
        number_of_employees:{
          $lte:500}},
          founded_year:{
            $gte:2000}},
          {$group: {
            _id: "$name"}, 
            description:"$description"},
            {$sort:{
              founded_year:1}}

])

我不确定是什么原因造成的,并且已经玩了一段时间了,任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 除了管道阶段的语法错误(主要是字段的大括号)之外,$group 也不能作为第二个字段,因为它应该是一个累加器。

标签: mongodb aggregation-framework


【解决方案1】:

查询中的管道阶段括号有问题

正确的排列方式应该是

db.HomeworkAggregate.aggregate([
        {$match:{
            number_of_employees:{
                $lte: 500
            },
            founded_year:{
                $gte: 2000
            }
        }},
        {$group: {
            _id: "$name", 
            description: {$first: "$description"} // you can use other operators also
            founded_year: {$first: "$founded_year"}
        }},
        {$sort:{
            founded_year: 1
        }}
    ])

您收到错误“管道阶段规范对象必须只包含一个字段”,因为存在一些无法识别的管道阶段,因为开括号和右括号不匹配。

其次,因为你是按“founded_year”排序的”。

另外,你应该在 $group 阶段使用$group accumulators

如果您仍然遇到任何问题,请分享,

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 2017-07-03
    • 2017-07-17
    • 1970-01-01
    • 2017-09-20
    • 2016-12-27
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多