映射数组导致 mongodb 聚合
Map array result in mongodb aggregation
我有以下 MongoDB 查询:
const vaccination = await Schedule.aggregate([
{ $match: { status: ScheduleStatus.Published } },
{ "$unwind": { "path": "$vaccines", "preserveNullAndEmptyArrays": true } },
{
"$group": {
"_id": "$vaccines.vaccine",
"count": { "$sum": "$vaccines.stok" },
}
},
{
$lookup: { from: 'vaccines', localField: '_id', foreignField: '_id', as: 'vaccine' },
},
{
$project: {
"count": 1,
"vaccine": { "$arrayElemAt": ["$vaccine.name", 0] }
}
}
]);
和return结果如下:
[
{
"_id": "61efd8a812432135c08a748d",
"count": 20,
"vaccine": "Sinovac"
}
]
有什么方法可以使输出成为一个值数组,例如:
[["Sinovac",20]]
感谢抱歉我的英语不好
所以你无法得到你要求的确切结构,根据聚合框架的定义return是一个“文档”数组,一个文档的形式是{key: value}
,什么但是你可以做的是 return 以下结构:
[
{
"values": [
"61efd8a812432135c08a748d",
20,
"Sinovac"
]
}
]
使用此管道:
db.collection.aggregate([
{
$project: {
_id: 0,
values: {
$map: {
input: {
"$objectToArray": "$$ROOT"
},
as: "item",
in: "$$item.v"
}
}
}
}
])
我有以下 MongoDB 查询:
const vaccination = await Schedule.aggregate([
{ $match: { status: ScheduleStatus.Published } },
{ "$unwind": { "path": "$vaccines", "preserveNullAndEmptyArrays": true } },
{
"$group": {
"_id": "$vaccines.vaccine",
"count": { "$sum": "$vaccines.stok" },
}
},
{
$lookup: { from: 'vaccines', localField: '_id', foreignField: '_id', as: 'vaccine' },
},
{
$project: {
"count": 1,
"vaccine": { "$arrayElemAt": ["$vaccine.name", 0] }
}
}
]);
和return结果如下:
[
{
"_id": "61efd8a812432135c08a748d",
"count": 20,
"vaccine": "Sinovac"
}
]
有什么方法可以使输出成为一个值数组,例如:
[["Sinovac",20]]
感谢抱歉我的英语不好
所以你无法得到你要求的确切结构,根据聚合框架的定义return是一个“文档”数组,一个文档的形式是{key: value}
,什么但是你可以做的是 return 以下结构:
[
{
"values": [
"61efd8a812432135c08a748d",
20,
"Sinovac"
]
}
]
使用此管道:
db.collection.aggregate([
{
$project: {
_id: 0,
values: {
$map: {
input: {
"$objectToArray": "$$ROOT"
},
as: "item",
in: "$$item.v"
}
}
}
}
])