我正在尝试为将组结果分为两个级别创建mongoquery。首先按文件夹,然后按名称。
收藏:
[
{
folder: "A",
name: "Apple",
color: "red"
},
{
folder: "A",
name: "Banana",
color: "green"
},
{
folder: "A",
name: "Apple",
color: "yellow"
},
{
folder: "B",
name: "Cherry",
color: "green"
}
]
预期结果:
{
A:{
Apple:[item1, item3]
Banana:[item2]
},
B:{
Cherry:[item4]
},
}
我已经有一个比较接近的结果,但是问题是我不能输入动态字段名称, 我的查询:
db.collection.aggregate([
{
$group: {
_id: {
folder: "$folder",
name: "$name"
},
files: {
$push: "$$ROOT"
},
},
},
{
"$group": {
"_id": "$_id.name",
"files": {
$push: {
"{ThisMustBeTheName}": "$files"
}
},
}
}
])
https://mongoplayground.net/p/Bq1qYZN7j4v
有什么建议吗?
答案 0 :(得分:1)
db.collection.aggregate([
{
$group: {
_id: {
folder: "$folder",
name: "$name"
},
files: {
$push: "$$ROOT"
},
},
},
{
"$group": {
"_id": "$_id.name",
"files": { //To make replace root syntax correct
$push: {
"k": "$_id.name",
"v": "$files"
}
}
}
},
{
"$replaceRoot": { //It does the dynamic naming part
"newRoot": {
"$mergeObjects": [
{
"$arrayToObject": "$files"
}
]
}
}
}
])
另一个更新:
db.collection.aggregate([
{
$group: {
_id: {
folder: "$folder",
name: "$name"
},
files: {
$push: "$$ROOT"
},
},
},
{
"$group": {
"_id": "$_id.name",
"files": {
$push: {
"k": "$_id.name",
"v": "$files"
}
},
"folder": {
$first: "$files.folder"
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
{
"$arrayToObject": "$files"
},
{
"folder": {
$first: "$folder"
}
}
]
}
}
},
{
"$group": {
"_id": "$folder",
"data": {
"$push": "$$ROOT"
}
}
},
{
$group: {
"_id": "$_id",
"d": {
$push: {
"k": "$_id",
"v": "$data"
}
}
}
},
{
"$replaceRoot": {
"newRoot": {
"$mergeObjects": [
{
"$arrayToObject": "$d"
}
]
}
}
}
])