文档的相关部分如下所示:
{
"map": {
"cities": [
{
"name": "City1",
"x": 15,
"y": 5,
"owner": 1,
"defense": 6,
"income": 35
},
{
"name": "City2",
"x": 12,
"y": 14,
"owner": 0,
"defense": 4,
"income": 16
},
{
"name": "City3",
"x": 6,
"y": 19,
"owner": 2,
"defense": 3,
"income": 12
}
]
},
"players": [
{
"userid": "64d3ebfb42fb5b118b928f5c",
"faction": 1
},
{
"userid": "636f89f0d4666b666237cec8",
"faction": 2
}
]
}
现在,如果我是玩家 1(用户 ID:“64d3ebfb42fb5b118b928f5c”),如何编写输出此内容的查询:
{
"map": {
"cities": [
{
"name": "City1",
"x": 15,
"y": 5,
"owner": 1,
"defense": 6,
"income": 35
},
{
"name": "City2",
"x": 12,
"y": 14,
"owner": 0
},
{
"name": "City3",
"x": 6,
"y": 19,
"owner": 2
}
]
}
}
对于玩家 2,它将返回(用户 ID:“636f89f0d4666b666237cec8”):
{
"map": {
"cities": [
{
"name": "City1",
"x": 15,
"y": 5,
"owner": 1
},
{
"name": "City2",
"x": 12,
"y": 14,
"owner": 0
},
{
"name": "City3",
"x": 6,
"y": 19,
"owner": 2,
"defense": 3,
"income": 12
}
]
}
}
- 查询应仅将用户 ID 作为输入
- 仅当“players.faction”与“map.cities.owner”匹配时,才会显示“防御”和“收入”的实际值
- 玩家不会看到他/她不拥有的城市的价值
- 另一种选择是,如果玩家不拥有城市,则这些值默认为 0
我知道我可以查询并以编程方式删除它,但我想知道是否可以做得更好。
我尝试这样做,但它显然不起作用,因为“$map.cities.owner”/“$map.cities.defense”实际上是/返回一个数组。
{
_id: 0,
"map.cities.name": 1,
"map.cities.x": 1,
"map.cities.y": 1,
"map.cities.owner": 1,
"map.cities.defense": {
$cond: {
if: {
$eq: ["$map.cities.owner", 1],
},
then: "$map.cities.defense",
else: "$$REMOVE",
},
},
}
我尝试使用$filter
,但这很快就变得非常麻烦,而且我从未得到我想要的结果。
我尝试使用$unwind
onmap.cities
但很难再次将其放入单个文档中。