我有一个像这样的收藏品:
{
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
},
...单个文档表示用户正在玩游戏。我如何找到这样一组用户:
我的想法是运行$group阶段与用户& gameCategory,并使用$match或其他东西过滤掉用户谁也玩其他类别的游戏
发布于 2022-05-26 17:32:38
编辑:这里有很多选项。这是一个简单的问题:
$group为每个用户存储其gameCategory,还可以检查他们是否在另一个游戏中玩,从而填充other。这允许我们只在groupType上存储作为组密钥的gameCategory。groupType只包含一个键,这是组键,否则是‘两者都’。other键为空时,才是正确的。$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://stackoverflow.com/questions/72395336
复制相似问题