PHP MongoDB聚合:查找分组依据_id

时间:2020-05-01 15:31:36

标签: php mongodb

我正在一个项目中,我试图通过下面的管道获取相关文档,但我不知道如何将结果分组并获得一组唯一的项目。

[
    {
        "$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及其两个孩子:

[
    {
        "_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
    }
]

1 个答案:

答案 0 :(得分:0)

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

在这里,我将其他管道添加到现有管道中:

[
    {
        "$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的更多信息,请参见here

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

希望这会有所帮助:)

相关问题