我有這個集合結構:
[
"_id": "61a013b59f9dd0ebfd23ftgb",
"modules": [
{
"_id": "61a013b59f9dd0ebfd964dgh",
"videos": [
{
"_id": "213412",
"progress": 100
},
{
"_id": "61a013b59f9dd0ebfd965f4a",
"progress": 0
},
]
},
{
"_id": "43556hujferwdhgsdft",
"videos": [
{
"_id": "fdsg3sg98er989890",
"progress": 66
},
{
"_id": "fdsg3sg98er989890",
"progress": 100
},
{
"_id": "fdsg3sg98er989890",
"progress": 100
}
]
}
]
]
我試圖通過將所有進度為 100 的視頻相加并根據模塊中的視頻數量創建百分比來回傳每個“模塊”的整體進度。例如,第一個模塊應該在其中回傳50 的“module_progess”,因為這已經完成了 1/2 的視頻。
{
"_id": "61a013b59f9dd0ebfd964dgh",
"module_progress": 50,
"videos": [
{
"_id": "213412",
"progress": 100
},
{
"_id": "61a013b59f9dd0ebfd965f4a",
"progress": 0
},
]
},
我如何訪問每個視頻物件以進行此計算并將新欄位添加到回應中?
uj5u.com熱心網友回復:
查詢1
- 模塊上的映射
- 并在每個欄位上添加一個包含視頻平均進度的欄位
測驗代碼在這里
aggregate(
[{"$set":
{"modules":
{"$map":
{"input": "$modules",
"in":
{"$mergeObjects":
["$$this",
{"module_progress":
{"$avg":
{"$map":
{"input": "$$this.videos.progress",
"in":
{"$cond": [{"$eq": ["$$progress", 100]}, "$$progress", 0]},
"as": "progress"}}}}]}}}}}])
查詢2
- 放松
- 替換根使結構更好
- 添加平均欄位
測驗代碼在這里
aggregate(
[{"$unwind": {"path": "$modules"}},
{"$replaceRoot": {"newRoot": "$modules"}},
{"$set":
{"module_progress":
{"$avg":
{"$map":
{"input": "$videos.progress",
"in": {"$cond": [{"$eq": ["$$this", 100]}, "$$this", 0]}}}}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372912.html
標籤:javascript MongoDB mongodb-nodejs-驱动程序
