MongoDB为每个类别添加Group标头

时间:2017-12-14 19:54:23

标签: mongodb mongodb-query aggregation-framework

需要帮助 Mongo 查询,我已经尝试过Query1和查询2(如下所示),但我无法解决。

我的输入数据:

[
  { "_id":1,    "make":"Honda",    "model":"Accord"  },
  { "_id":2,    "make":"Toyota",   "model":"Camry"  },
  { "_id":3,    "make":"Honda",    "model":"Civic"  },
  { "_id":4,    "make":"Subaru",   "model":"Legacy"  },
  { "_id":5,    "make":"Subaru",   "model":"Outback"  },
  { "_id":6,    "make":"Toyota",   "model":"Corrola"  }
]

我需要以下输出,我们为每个 组或类别 设置 新标题 (本田/丰田/斯巴鲁)

[
    {   "description" : "Honda" },
    {   "description" : "Honda - Accord"    },
    {   "description" : "Honda - Civic"     },
    {   "description" : "Subaru"    },
    {   "description" : "Subaru - Legacy"   },
    {   "description" : "Subaru - Outback"  },
    {   "description" : "Toyota"    },
    {   "description" : "Toyota - Camry"    },
    {   "description" : "Toyota - Corrola"  }
]

查询1:

db.cars.aggregate([
   { $sort : { make : 1, model:1 } },
   { $project: {"_id":0, "description":{ $concat: [ "$make", " - ", "$model" ]} } }
])

通过上述查询,我​​能够连接Make和Model ,但我无法为唯一的make 插入新标题。

查询1的结果:

[
    {   "description" : "Honda - Accord"    },
    {   "description" : "Honda - Civic"     },
    {   "description" : "Subaru - Legacy"   },
    {   "description" : "Subaru - Outback"  },
    {   "description" : "Toyota - Camry"    },
    {   "description" : "Toyota - Corrola"  }
]

查询2:尝试使用$reduce

db.cars.aggregate([
    { $sort: { make: 1, model: 1 }},
    { $group: {
            "_id": "$make",
            models: {
                $push: {
                    $concat: ["$make", " - ", "$model"]
                }
            }
        }
    },
    { $project: {
            "_id": 0,
            "description": {
                $reduce: {
                    input: "$models",
                    initialValue: "$_id",
                    in: {
                        $concatArrays: ["$$value", "$$this"]
                    }
                }
            }
        }
    }
])

查询2 我收到了以下异常

"errmsg" : "$concatArrays only supports arrays, not string",
"code" : 28664,

2 个答案:

答案 0 :(得分:2)

您也可以尝试以下聚合。

db.cars.aggregate([
  {"$sort":{"make":1,"model":1}},
  {"$group":{"_id":"$make","description":{"$push":{"$concat":["$make"," - ","$model"]}}}},
  {"$project":{"_id":0,"description":{"$concatArrays":[["$_id"],"$description"]}}},
  {"$unwind":"$description"}
])

答案 1 :(得分:1)

试试这个:

db.cars.aggregate([{
    $group: {
        _id: "$make",
        models: { $push: { $concat: [ " - ", "$model" ] } } // push all existing "model"s plus the " - " at the start into an array per "make"
    }
}, {
    $addFields: {
        models: { $concatArrays: [ "$models", [ "" ] ] } // we push an empty item into the array
    }
}, {
    $unwind: "$models" // flatten the array again
},
   { $sort : { _id : 1, models: 1 } },
   { $project: {"_id": 0, "description": { $concat: [ "$_id", "$models" ] } } }
])