我需要使用 mongoose 创建一个查询,它允许我使用该组,对处于 STARTED 或 NOT INITIATED 状态的元素进行计数,然后返回处于每个状态的元素的计数。
这是我正在使用的 json 对象。
[
{
status: "INITIATED",
_id: "6057e0013a3dec1d44a7d152",
group: "dairy",
location: "001",
total_items: 30,
__v: 0
},
{
status: "INITIATED",
_id: "6057e0013a3dec1d44a7d153",
group: "dairy",
location: "002",
total_items: 45,
__v: 0
},
{
status: "INITIATED",
_id: "6057e0013a3dec1d44a7d154",
group: "dairy",
location: "003",
total_items: 12,
__v: 0
},
{
status: "NOT INITIATED",
_id: "6057e0013a3dec1d44a7d155",
group: "dairy",
location: "004",
total_items: 50,
__v: 0
},
{
status: "NOT INITIATED",
_id: "6057e0013a3dec1d44a7d156",
group: "drugs",
location: "005",
total_items: 23,
__v: 0
},
{
status: "NOT INITIATED",
_id: "6057e0013a3dec1d44a7d157",
group: "drugs",
location: "006",
total_items: 76,
__v: 0
}]
例如,我需要从乳制品组返回具有以下结构的 json。
{
'id': null,
'group': 'dairy',
'INITIATED': 3,
'NO INITIATED': 1
}
由于乳制品组,其中 3 个元素处于 STARTED 状态,其中一个元素处于 NOT INITIATED 状态。另一个示例是应返回以下 json 的药物组。
{
'id': null,
'group': 'medications',
'STARTED': 0,
'NOT INITIATED': 2
}
为了做到这一点,我正在尝试让以下代码工作。
db.collection.aggregate ([
{
"$ group": {
_id: {
source: "$ group",
status: "$ status"
},
count: {
$ sum: 1
}
}
}
])
但我不太清楚如何使用该组来生成我需要的响应。
最佳答案
好吧,这比我一开始想象的要棘手,但你可以这样做:
首先,按组字段对文档进行分组,并对状态字段的计数进行求和。我使用 $cond
和 $eq
运算符来确保状态与计数字段匹配。最后,您应用 $project
来获得所需的输出,而无需 _id
字段:
db.collection.aggregate([
{ "$group": {
"_id": "$group",
"NOT INITIATED": {
"$sum": {
"$cond": [ { "$eq": [ "$status", "NOT INITIATED" ] }, 1, 0]
}
},
"INITIATED": {
"$sum": {
"$cond": [ { "$eq": [ "$status", "INITIATED" ] }, 1, 0]
}
},
} },
{ "$project": {
"_id": 0,
"group": "$_id",
"INITIATED":1,
"NOT INITIATED":1
} }])
我在 mongoplayground 上为您创建了一个示例:https://mongoplayground.net/p/H-72VzWoeoN
关于javascript - 如何使用 Mongoose 将两个元素分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66754377/