我想從 MongoDB 獲得流行的產品。這是我的架構;
...
user: {
type: mongoose.Types.ObjectId,
ref: 'users'
},
rating: [{
user : {
type: mongoose.Types.ObjectId,
ref: 'users'
},
rate: {
type: Number,
min: 1,
max: 5
}
}],
created_at : {
type : Date
},
...
我想按rating.rate總和訂購。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
這里有一個解決方案:
db.collection('products').aggregate([
{
"$unwind": "$rating"
},
{
$group: {
_id: "$_id",
sum: {
"$sum": "$rating.rate"
},
}
},
{
"$sort": {
"sum": -1
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503986.html
標籤:javascript 节点.js 猫鼬
