MongoDB:汇总 Statis Key value 和 Total count
MongoDB: aggregate Statis Key value and Total count
我有一个总计数数据。但我需要 Statis 对象和 Totoal Counts。
我的示例数据
{
"_id" : ObjectId("6218b5f0405919280c209f73"),
"inspectionResult" : "Passed",
"projectId" : ObjectId("6218a31f405919280c209e18"),
"accountId" : ObjectId("621888e852bd8836c04b8f82"),
"dateInspected" : ISODate("2022-03-08T00:00:00.000Z"),
}
我的聚合查询
db.getCollection('welds').aggregate([
{
$match: {
accountId: ObjectId("621888e852bd8836c04b8f82"),
projectId: ObjectId("6227089af6d4162e9c57d8be"),
}
},
{
$facet: {
'PostWeldInspection': [
{
$project: {
_id: 0,
x: 'PWI',
dateInsp: '$dateInspected',
}
},
{ $count: 'Y' }
],
}
}
])
我的结果:
{
"PostWeldInspection" : [
{
"Y" : 62
}
]
}
但我需要静态对象和总计数,如下所示,
{
"PostWeldInspection" : [
{
"x" : "PWI",
"Y" : 62
}
]
}
提前致谢。
这只是 $count 阶段行为,您可以只使用 $group
阶段来保留其他字段。文档还指定这是等效的:
The $count stage is equivalent to a $group + $project sequence:
db.collection.aggregate([
{
$match: {
accountId: ObjectId("621888e852bd8836c04b8f82"),
projectId: ObjectId("6227089af6d4162e9c57d8be"),
}
},
{
$facet: {
"PostWeldInspection": [
{
$project: {
_id: 0,
x: "PWI",
dateInsp: "$dateInspected",
}
},
{
$group: {
_id: null,
x: {
$first: "$x"
},
dateInsp: {
$first: "$dateInsp"
},
Y: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
}
}
],
}
}
])
我建议使用 this 简化版本,因为我不确定你为什么将 $facet
合并到你的管道中。
我有一个总计数数据。但我需要 Statis 对象和 Totoal Counts。
我的示例数据
{
"_id" : ObjectId("6218b5f0405919280c209f73"),
"inspectionResult" : "Passed",
"projectId" : ObjectId("6218a31f405919280c209e18"),
"accountId" : ObjectId("621888e852bd8836c04b8f82"),
"dateInspected" : ISODate("2022-03-08T00:00:00.000Z"),
}
我的聚合查询
db.getCollection('welds').aggregate([
{
$match: {
accountId: ObjectId("621888e852bd8836c04b8f82"),
projectId: ObjectId("6227089af6d4162e9c57d8be"),
}
},
{
$facet: {
'PostWeldInspection': [
{
$project: {
_id: 0,
x: 'PWI',
dateInsp: '$dateInspected',
}
},
{ $count: 'Y' }
],
}
}
])
我的结果:
{
"PostWeldInspection" : [
{
"Y" : 62
}
]
}
但我需要静态对象和总计数,如下所示,
{
"PostWeldInspection" : [
{
"x" : "PWI",
"Y" : 62
}
]
}
提前致谢。
这只是 $count 阶段行为,您可以只使用 $group
阶段来保留其他字段。文档还指定这是等效的:
The $count stage is equivalent to a $group + $project sequence:
db.collection.aggregate([
{
$match: {
accountId: ObjectId("621888e852bd8836c04b8f82"),
projectId: ObjectId("6227089af6d4162e9c57d8be"),
}
},
{
$facet: {
"PostWeldInspection": [
{
$project: {
_id: 0,
x: "PWI",
dateInsp: "$dateInspected",
}
},
{
$group: {
_id: null,
x: {
$first: "$x"
},
dateInsp: {
$first: "$dateInsp"
},
Y: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
}
}
],
}
}
])
我建议使用 this 简化版本,因为我不确定你为什么将 $facet
合并到你的管道中。