【问题标题】:Why mongo aggregate not return a consistent order?为什么 mongo 聚合不返回一致的顺序?
【发布时间】:2021-11-05 02:50:09
【问题描述】:

这是我的查询:

db.getCollection('alerts').aggregate([{
  $match: {
    houseId: ObjectId("609100a56ed9f8001351aee3")
  }
}, {
    $group: {
        _id: '$type',
        alerts: {
            $push: {
                _id: '$_id',
                type: '$type'
            }
        }
     }
  },
  {
    $project: {
       _id: false,
       type: '$_id.type',
       alerts: '$alerts'
    }

  }
])

结果:

[{
    "type" : "cool",
    "alerts" : [ 
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "cool"
        }
    ]
}, {
    "type" : "hot",
    "alerts" : [ 
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "hot"
        },
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "hot"
        }
    ]
}]

但有时它也会返回:

[{
    "type" : "hot",
    "alerts" : [ 
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "hot"
        },
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "hot"
        }
    ]
}, {
    "type" : "cool",
    "alerts" : [ 
        {
            "_id" : ObjectId("61387e740dc3d853f1eee5b0"),
            "type" : "cool"
        }
    ]
}]

我为分页添加了一个阶段 $limit 和 $skip,如果 skip: 0, limit: 1 那么第一条记录有时很酷,有时很热。我也尝试添加阶段 $sort 以使顺序一致,但它不起作用。

我的带有排序和限制的脚本,跳过

db.getCollection('alerts').aggregate([{
  $match: {
    houseId: ObjectId("609100a56ed9f8001351aee3")
  }
}, {
    $group: {
        _id: '$type',
        alerts: {
            $push: {
                _id: '$_id',
                type: '$type'
            }
        }
     }
  },
  {
    $project: {
       _id: false,
       type: '$_id.type',
       alerts: '$alerts'
    }

  },
  {
    $limit: limit + skip,
  },
  {
    $skip: skip,
  },
  {
    $sort: { type: 1 }
  }
])

我的预期是结果返回相同的顺序

【问题讨论】:

  • 你能提供排序对象吗?
  • $group 阶段之前插入阶段{$sort: {type: 1}}
  • @mohammadNaimi { 排序:{ 类型:1 }}
  • @WernfriedDomscheit 我在最后阶段推送它。因为我认为在限制之后,跳过结果可能会减少并且排序运算符会更快。但是排序不起作用。
  • 你是否在聚合中添加了跳过和限制?

标签: mongodb aggregate


【解决方案1】:
db.getCollection('alerts').aggregate([{
  $match: {
    houseId: ObjectId("609100a56ed9f8001351aee3")
  }
}, {
    $group: {
        _id: '$type',
        alerts: {
            $push: {
                _id: '$_id',
                type: '$type'
            }
        }
     }
  },
  {
    $project: {
       _id: false,
       type: '$_id.type',
       alerts: '$alerts'
    }

  },
  {
    $sort: { type: 1 }
  },
  {
    $skip: skip,
  },
  {
    $limit: limit + skip,
  }
])

我改变了sort,limitskip的顺序

【讨论】:

  • 如果我将它推到跳过和限制以下,为什么排序不起作用?
  • 添加排序上限并跳过
  • 我想知道如果排序低于跳过,限制,为什么排序不起作用
  • 我认为返回上一阶段($group)的原因,该阶段的结果没有排序,当你申请限制和跳过它会随机返回,最后阶段的排序不一样每个查询
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多