假設給定以下資料:
[
{
_id: 61708f71ee435de97b5a82e7,
title: 'mjGPzpGLKIdea Title',
author: 61708f6dee435de97b5a82e2
votes: [
6171c8437234d56cfeff9986,
6171c8647234d56cfeff99de
]
},
{
_id: 6171c522069a2f6b396a430a,
title: 'MnJYCZFtyIdea Title',
author: 61708f7cee435de97b5a82f2,
votes: [ 6171c8927234d56cfeff9a45 ],
},
{
_id: 6171c523069a2f6b396a4315,
title: 'pcOKJzOEAIdea Title',
author: 61708f7cee435de97b5a82f2,
votes: [
6171c8327234d56cfeff9950,
6171c83c7234d56cfeff9967,
6171c85d7234d56cfeff99bb,
6171c8817234d56cfeff9a11
]
}
]
每個投票votes都有這樣的結構:
{
_id: 6171c8817234d56cfeff9a11, // some id
score: -1, // -1 or 1
}
如何使用 Mongoose 在每個專案中獲得相同的陣列但分數降低:
[
{
_id: 61708f71ee435de97b5a82e7,
title: 'mjGPzpGLKIdea Title',
author: 61708f6dee435de97b5a82e2
scoreSum: 0 // -1 1
},
{
_id: 6171c522069a2f6b396a430a,
title: 'MnJYCZFtyIdea Title',
author: 61708f7cee435de97b5a82f2,
scoreSum: -1,
},
{
_id: 6171c523069a2f6b396a4315,
title: 'pcOKJzOEAIdea Title',
author: 61708f7cee435de97b5a82f2,
scoreSum: 3 // 1 1 1 - 1
}
]
我嘗試將$reduce聚合與一起使用$add,但最終$$this.score回傳了我null。像這樣:
MyModel.aggregate([
{
$addFields: {
scoreSum: {
$reduce: {
input: '$votes',
initialValue: 0,
in: { $add: ['$$value', '$$this.score'] },
},
},
},
},
])
我不想使用 javascript,我只想使用對資料庫的請求并減少元素中的值。謝謝你。
uj5u.com熱心網友回復:
我不知道你做錯了什么,但你也需要查找。
詢問
- 查找連接具有單個欄位的陣列
(如果votes陣列包含該欄位,則連接發生_id) - 減少和求和分數
"$$REMOVE"是一個系統變數來移除欄位投票,你可以避免它和project或unset欄位votes
測驗代碼在這里
authors.aggregate(
[{"$lookup":
{"from": "votes",
"localField": "votes",
"foreignField": "_id",
"as": "scoreSum"}},
{"$set":
{"scoreSum":
{"$reduce":
{"input": "$scoreSum",
"initialValue": 0,
"in": {"$add": ["$$value", "$$this.score"]}}},
"votes": "$$REMOVE"}}])
有$lookup使用管道的替代解決方案,而不是減少,按空和總和分組,但這看起來更像是您的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330476.html
上一篇:分組內的ggplot百分比
