下面是我的 mongodb 結構:
[{
countries: ["US"],
type: "4"
},
{
countries: ["IN"],
type: "4"
},
{
countries: ["US"],
type: "4"
}
]
注意:countries對于這種情況,陣列在陣列中只有一項
我希望分組并計算在哪里,type === 4以便結果是:
[{
countries: ["US"],
count: 2
},{
countries: ["IN"],
count: 1
}]
好吧,我嘗試使用這樣的聚合,但我認為我錯了:
const aggregatorOpts = [{
$group: {
_id: "$countries",
count: { $sum: 1 }
}
}]
Model.aggregate(aggregatorOpts).exec()
任何有關如何進行聚合的幫助都可能受到贊賞。
提前致謝!
uj5u.com熱心網友回復:
這是你想要的嗎?你需要先做一個 $match 。 https://mongoplayground.net/p/UuOF53E44tG
db.collection.aggregate([
{
$match: {
type: {
$eq: "4"
}
}
},
{
$group: {
_id: "$countries",
count: {
$sum: 1
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362485.html
