php - 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
}
]
解决方案
由于您需要获取_id
and的值title
,因此您必须对_id
and进行分组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
请参阅此处。
这将为您提供所需的输出。
希望这会有所帮助:)
推荐阅读
- c++ - C++ 反转迭代器
- scala - 在尝试使用“TABLE_NAME.insert”将数据插入分区表时获取“单分区插入语句中的错误分区元组”
- openlayers - openlayers 5.3 和 heatmap-layer 的问题(瓷砖看起来有缺陷)
- javascript - 在 ASP.Net Core 2.x 中使用 ES6 模块导入运行 javascript 文件
- user-interface - 有没有办法创建一个带有固定在右上角的 domino-ui 组件的聊天框?
- android-layout - 微调器被衬垫布局的背景隐藏
- performance - 为什么返回 Springboot ResponseEntitty 这么慢?
- sharepoint - 使用 Sharepoint Flow 从 Office 文档中提取关键字
- javascript - 将元素与另一个数组匹配的数组过滤对象(具有键“id”)
- testing - 如何从 testcafe 框架自定义 testRunner?