【问题标题】:Mongo query based on count and if count is same then alphabeticallyMongo 基于计数的查询,如果计数相同,则按字母顺序
【发布时间】:2022-08-09 01:03:17
【问题描述】:

我有一个优惠券集合,我正在尝试根据代码对所有优惠券进行分组。之后,我想根据计数对它们进行排序。直到这个查询工作正常。但在此之后,如果优惠券代码的计数相同,那么它应该根据另一个键对它们进行排序。在这里,我尝试根据优惠券代码对其进行排序。但是每次我运行查询时,订单都不一样,并且没有根据优惠券代码正确排序。我附上猫鼬查询

const coupons = await Coupons.aggregate([
  { $match: couponFilter },
  {
    $group: {
      _id: \"$code\",
      count: { $sum: 1 },
    },
  },
  { $sort: { count: -1, code: 1 } },
  { $skip: skip },
  { $limit: limit },
  { $project: { code: \"$_id\", count: 1, _id: 0 } },
]);

通常它应该可以正常工作,但不能正常工作。每次我运行此查询时,它都会以不同的顺序返回项目。虽然,项目是根据计数正确排序的,但是当某些优惠券具有相同的计数时,它们不会根据优惠券代码正确排序。

无法将返回的数据附加为文本,因此将其附加为图像。这些是我执行3次查询时返回的数据截图,每次相同数量的优惠券代码顺序不同。

    标签: node.js mongodb mongoose nosql aggregation-framework


    【解决方案1】:

    $sort 阶段无效,因为 code 字段未包含在 $group 中。

    $sort 阶段更新了管道:

    const coupons = await Coupons.aggregate([
      { $match: couponFilter },
      {
        $group: {
          _id: "$code",
          count: { $sum: 1 },
        },
      },
      { $sort: { count: -1, _id: 1 } },
      { $skip: skip },
      { $limit: limit },
      { $project: { code: "$_id", count: 1, _id: 0 } },
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 2019-01-28
      • 2022-01-24
      相关资源
      最近更新 更多