【发布时间】:2022-11-24 03:32:42
【问题描述】:
我有 collection: bookSchema 作为:
[
{
_id: ObjectId("637d05dc32428ed75ea08d09"),
book_details: {
book_subscription: null,
book_auth: "Amber"
},
book_name: "random123"
},
{
_id: ObjectId("637d0673ce0f17f6c473dee2"),
book_details: {
book_subscription: ObjectId("637d06a545a17f0e686ecf3a"),
book_auth: "Shurya"
},
book_name: "random321"
},
{
_id: ObjectId("637d069a3d597c8458ebe4ec"),
book_details: {
book_subscription: ObjectId("637d06ac82f0760b03fdea0d"),
book_auth: "Aman"
},
book_name: "random676"
},
{
_id: ObjectId("637d06c05b32d503007bcb54"),
book_details: {
book_subscription: null,
book_auth: "Saurav"
},
book_name: "random999"
},
]
所需的 O/P 显示为:
{
score_ambr: 3,
score_saurabh: 1
}
为此,我试过:
db.bookSchema.aggregate([
{
"$group": {
"_id": {
"$eq": [
"$book_details.book_auth",
"Amber"
]
},
"score_ambr": {
"$sum": 1
}
},
},
{
"$group": {
"_id": {
"$eq": [
"$book_details.book_auth",
"Saurav"
]
},
"score_saurabh": {
"$sum": 1
}
},
}
])
我尝试使用 $group 来因为我想将所有匹配的文档组合成一个并使用 $count 来给出匹配文档的计数但它似乎不起作用并将 O/P 指定为
订单:
[
{
"_id": false,
"score_sau": 2
}
]
MongoDB游乐场:https://mongoplayground.net/p/cZ64KwAmwlv
【问题讨论】:
-
3 和 1 是什么意思,您是否总是使用 score_sau 和 score_abr 对查询进行硬编码
标签: javascript mongodb mongoose mongodb-query