【问题标题】:How to improve aggregation query in mongoDB?如何改进 mongoDB 中的聚合查询?
【发布时间】:2017-06-23 19:03:53
【问题描述】:

假设我有这 2 个巨大的文件:

[
 {
  _id: ....,
  status: "A",
  class: "DIP1A",
  "created.user._id": ...,
  "created.dt": ....,
  "category": "private",
  price: 100.00 //type double
 },
 {
  _id: ....,
  status: "A",
  class: "DIP2A",
  "created.user._id": ...
  "created.dt": ...,
  "category": "public",
  price: 200.00 //type double
 },
];

查询:

    var pipeline = [

              {
                $match: {
                  "created.user._id": ....
                }
              },
              {
                $unwind: "$class"
              },
              {
                $unwind: "$price"
              },
              {
                $group: {
                  _id: "$class",
                  price: {
                    $sum: "$price"
                  },
                  count: {
                    $sum: 1
                  }
                }
              },
              {
                $project: {
                  _id: 0,
                  class: '$_id',
                  count: 1,
                  price: 1
                }
              }
    ];

 db.myCollection.aggregate(pipeline);

问题问题:

  • 不带calculate/$sum "$price"的查询,运行速度确实更快;

索引:

db.myCollection.ensureIndex({ 'created.user._id': -1 });
db.myCollection.ensureIndex({ 'created.user._id': -1, class: 1 });
db.myCollection.ensureIndex({ 'created.user._id': -1, price: 1});

性能:

  • 没有 $sum calc:5 秒有大量记录。
  • $sum cals:20 分钟,记录大量记录。

【问题讨论】:

  • 你能添加两个查询的解释吗?要得到它,运行 db.myCollection.aggregate(pipeline, {explain: true})

标签: node.js mongodb aggregation-framework


【解决方案1】:

您真正应该做的一件事是将 $project 阶段移到 $match 阶段之后(如果文档包含更多数据,然后在您的问题中说明(大量文档))。 您希望通过管道尽可能少的数据。 我还看到价格和类别的 $unwind 但在您的示例中它们不是数组。这可能是复制/粘贴问题;-)

喜欢:

var pipeline = [

          {
            $match: {
              "created.user._id": ....
            }
          },
         {
            $project: {
              _id: 0,
              class: '$_id',
              count: 1,
              price: 1
            }
          },
          {
            $unwind: "$class"
          },
          {
            $unwind: "$price"
          },
          {
            $group: {
              _id: "$class",
              price: {
                $sum: "$price"
              },
              count: {
                $sum: 1
              }
            }
          },
];

【讨论】:

    猜你喜欢
    • 2019-06-18
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多