$ unwind,除“路径”目标外,还产生结果补充

时间:2019-09-05 21:59:25

标签: mongodb

我有一个名为scorerecords的mongo集合,其中包含如下文档:

{status: 'in progress', teams: {count: 2, team: [ {name: "team 1", score: 100}, {name: "team 2", score: 95}]}}

我想为“ teams.team”数组中的每个元素返回唯一的记录(可以使用$ unwind来完成),但是还要返回相反的团队记录(“对手”)。示例:

{status: 'in progress', teams: {count: 2, team: {name: "team 1", score: 100}, opponent: {name: "team 2", score: 95}}}
{status: 'in progress', teams: {count: 2, team: {name: "team 2", score: 95}, opponent: {name: "team 1", score: 100}}}

这样,我每个团队有1条记录(而不是每场比赛1条),并且可以计算团队获胜或失败的次数(例如,使用$ project语句定义“ winner:true / false” “字段或类似内容)。

是否可以通过$ aggregate函数(例如$ project / $ unwind)的某些组合来做到这一点?

1 个答案:

答案 0 :(得分:0)

我最终找到了解决方法:

db.scorerecords.aggregate([{$addFields: {"teams.team": {$map: {input: "$teams.team", as: "tm", in: {"name": "$$tm.name", "score":"$$tm.score", "idx": {$indexOfArray: ["$teams.team", "$$tm"]} }}}}},{$addFields: {"teams.team": {$map: {input: "$teams.team", as: "tm", in: {"name": "$$tm.name", "score": "$$tm.score", "opp": {$arrayElemAt: ["$teams.team", {$subtract: [1, "$$tm.idx"]}]}} }}}}, {$unwind: "$teams.team"} ])

似乎可能有一种更方便/有效的方法,但是这种方法似乎返回了所需的结果。

步骤: 1)添加一个字段,该字段使用$ map调用标识数组中当前项目的“索引”。 2)使用另一个$ map调用,添加一个“ opp”字段,并假设opp是数组中的第(1-idx)个条目(请参见下面的注意事项)。 3)使用$ unwind展平,创建2x原始记录集,其中包括补充记录。

第2步的警告: (这假设每个得分记录将具有<= 2个团队。如果只有1个,则不会填充“ opp”字段,这是可取的。如果“团队”中有2个以上的团队,则会产生意外结果。团队”数组。(例如,对于第二个以后的每个团队,它将返回数组中的最后一个元素作为“ opp”)。