我有一個看起來像這樣的集合:
{
id: 1
user: 1
gameCategory: aaa/traditional
gameName: Artifact
},
{
id: 2
user: 1
gameCategory: web3
gameName: Axie Infinity
},
{
id: 3
user: 2
gameCategory: aaa/traditional
gameName: League of Legends
},
...
單個檔案表示用戶正在玩游戲。我如何找到以下用戶組:
- 只玩“aaa/傳統”游戲
- 只玩“web3”游戲
- 玩兩種型別的游戲
我的想法是使用 user & gameCategory 運行 $group 階段,并使用 $match 或其他東西過濾掉也玩其他類別游戲的用戶
uj5u.com熱心網友回復:
編輯:這里有很多選擇。這是一個簡單的:
- 我們使用
$group為每個用戶存盤它的gameCategory,但也檢查他們是否在玩另一個游戲,因此填充other。這允許我們groupType只存盤gameCategory一個組的密鑰 - 如果
groupType只包含一個鍵,這是組鍵,否則是'both' - 僅當
otherkey 為空時才適用。 $group按groupType并聚合組的用戶
db.collection.aggregate([
{
$group: {
_id: "$user",
other: {
$addToSet: {
$cond: [
{$and: [{$ne: ["$gameCategory", "web3"]},
{$ne: ["$gameCategory", "aaa/traditional"]}]
}, "true", "$$REMOVE"]
}
},
groupType: {
$addToSet: {
$cond: [
{$or: [{$eq: ["$gameCategory", "web3"]},
{$eq: ["$gameCategory", "aaa/traditional"]}]
}, "$gameCategory", "$$REMOVE"]
}
}
}
},
{
$project: {
other: {$size: "$other"},
groupType: {
$cond: [{$eq: [{$size: "$groupType"}, 1]}, {$arrayElemAt: ["$groupType", 0]},
"both"
]
}
}
},
{$project: {groupType: {$cond: [{$eq: ["$other", 1]}, "other", "$groupType"]}}},
{$group: { _id: "$groupType", users: {$push: "$_id"}}}
])
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482022.html
上一篇:Mongodb復雜更新所有檔案
下一篇:更新收藏以更改排名
