首页 > 解决方案 > PHP MongoDB 聚合:查找 Groupby _id

问题描述

我正在一个项目中工作,我正在尝试使用下面的管道获取相关文档,但我不知道如何对结果进行分组并获得一组独特的项目。

[
    {
        "$match": {
            "id_site": 3,
            "id_parent": null,
            "id_class": null
        }
    },
    {
        "$lookup": {
            "from": "categories",
            "localField": "_id",
            "foreignField": "id_parent",
            "as": "Childs"
        }
    },
    {
        "$unwind": {
            "path": "$Childs",
            "preserveNullAndEmptyArrays": true
        }
    }
]

执行后,我得到了这个结果,我不知道如何按 _id 对结果进行分组并获得类别 1 - 级别 1 和他的 2 个孩子:

[
    {
        "_id": "5eac058490ba016d4942f782",
        "id_parent": null,
        "id_site": 3,
        "title": "Category 1 - Level 1",
        "Childs": {
            "_id": "5eac062590ba016d4942f783",
            "id_parent": "5eac058490ba016d4942f782",
            "id_site": 3,
            "title": "SubCategory 1 - Level 1",
            "Childs": null
        }
    },
    {
        "_id": "5eac058490ba016d4942f782",
        "id_parent": null,
        "id_site": 3,
        "title": "Category 1 - Level 1",
        "Childs": {
            "_id": "5eac324b423ea324bb762022",
            "id_parent": "5eac058490ba016d4942f782",
            "id_site": 3,
            "title": "SubCategory 2 - Level 1",
            "Childs": null
        }
    },
    {
        "_id": "5eac05d6684e587ee43af842",
        "id_parent": null,
        "id_site": 3,
        "title": "Category 2 - Level 1",
        "Childs": null
    },
    {
        "_id": "5eac05f50aa60f05b50faa92",
        "id_parent": null,
        "id_site": 3,
        "title": "Category 3 - Level 1",
        "Childs": null
    }
]

标签: phpmongodb

解决方案


由于您需要获取_idand的值title,因此您必须对_idand进行分组title

在这里,我将进一步的管道添加到现有管道:

[
    {
        "$match": {
            "id_site": 3,
            "id_parent": null,
            "id_class": null
        }
    },
    {
        "$lookup": {
            "from": "categories",
            "localField": "_id",
            "foreignField": "id_parent",
            "as": "Childs"
        }
    },
    {
        "$unwind": {
            "path": "$Childs",
            "preserveNullAndEmptyArrays": true
        }
    },
    {
      $group:{
        "_id":{
          "id":"$_id",
          "title":"$title"
        },
        "title":{
          $first:"$title"
        },
        "children":{
          $push:"$childs"
        }
      }
    },
    {
      $project:{
        "_id":0
      }
    }
]

此外,如果您需要一个独特的child价值观$addToSet,而不是$push在小组赛阶段使用。

有关更多信息,$group请参阅此处

这将为您提供所需的输出。

希望这会有所帮助:)


推荐阅读