如何在 mongodb 聚合中返回过滤后的数据和唯一值

问题描述 投票:0回答:0

我有以下管道:

[
  {
    $project: {
      _id: 0,
      id: 1,
      uniqueId: 1,
      shortLabel: 1,
      "geographicLocation.name": 1,
      "economicConcept.name": 1,
      "frequency.name": 1,
      "scale.name": 1,
      "unit.name": 1,
      source: 1,
    },
  },
  {
    $match: {
      $and: [
        {
          $or: [
            {
              "geographicLocation.name":
                "United States",
            },
            {
              "geographicLocation.name": "Singapore",
            },
          ],
        },
        {
          $or: [
            {
              source: {
                $elemMatch: {
                  name: {
                    $regex: "New",
                    $options: "i",
                  },
                },
              },
            },
          ],
        },
      ],
    },
  },
  {
    $facet: {
      metadata: [
        { $count: "total" },
        { $addFields: { page: 1 } },
      ],
      data: [{ $skip: 0 }, { $limit: 10 }],
    },
  },
]

返回过滤后的数据集。

为此,我还想获得一些数据集属性的唯一值,所以我添加了这一步:

   {
        "$group": {
            "_id": null,
            "distinctRegion": { "$addToSet": "$geographicLocation.name" },
            "distinctFrequency": { "$addToSet": "$frequency.name"},
            "distinctConcept": { "$addToSet": "$economicConcept.name" }
        }
    },

但是添加这个之后,我没有得到过滤后的数据结果,只有唯一值作为这个管道的输出。 有什么办法可以兼得吗?我想从该输出中获取过滤后的数据集和唯一值。

mongodb pymongo
© www.soinside.com 2019 - 2024. All rights reserved.