假设我的cardgame matches收藏中有这样的文档:
{
match_id: 1,
players: [
{
cards: [ "c03", "c15", "c22" ],
result: 1
},
{
cards: [ "c01", "c22", "c23" ],
result: 0
}
]
}
现在我想确定哪些牌被玩过,以及多久玩一次,这意味着所有cards
数组的列表,而不是两个特定牌数组相遇的事件列表。
我试过这样的方法,按比赛分组:
db.collection.aggregate([{
$group: {
_id: "$players.cards",
count: { $sum: 1 }
}
}])
实际结果:
[
{
"_id": [
[ "c03", "c15", "c22" ],
[ "c01", "c22", "c23" ]
],
"count": 3
},
...
]
预期结果:
[
{
"_id": [ "c03", "c15", "c22" ],
"count": 7
},
{
"_id": [ "c01", "c22", "c23" ],
"count": 5
},
...
]
我如何获得一组不同的牌组,而不考虑具体的匹配?
1条答案
按热度按时间ebdffaop1#
您的
players
字段是一个数组,您需要一个$unwind
阶段来将players
数组反构造为多个文档,以避免产生包含嵌套数组的_id
(组)的结果。Demo @ Mongo Playground