我在 Mongoose 中有一个名为 Points 的集合,其中我有用户所有积分的历史记录
这是点架构
const PointSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
reason: {
type: String,
required: true,
},
points: {
type: Number,
required: true,
},
time: {
type: Date,
default: Date.now,
},
});
我想要这样的 JSON 输出
{
"points": 30,
"history": [
{ Point object },
{ Point object },
{ Point object },
]
}
如果我有特定用户的id,如何获得特定用户查询的所有点的总和,并获得如上的输出?
最佳答案
您可以先做一个简单的聚合 $match
用户 ID,然后 $sum
所有的点最后将每个文档推送到history
数组:
db.collection.aggregate([
{
"$match": {
user: "<user-id-to-match>"
}
},
{
"$group": {
"_id": "$user",
"points": {
$sum: "$points"
},
history: {
"$push": "$$ROOT"
}
}
},
{
$project: {
_id: 0
}
}
])
这是我在 mongoplayground 创建的一个示例:https://mongoplayground.net/p/Q_TtcI_dkZu
关于node.js - Mongoose:特定用户查询的所有点的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64537245/