我有一个深层嵌套的文档结构,如下所示:
{id: 1,
forecasts: [ {
forecast_id: 123,
name: "Forecast 1",
levels: [
{ level: "proven",
configs: [
{
config: "Custom 1",
variables: [{ x: 1, y:2, z:3}]
},
{
config: "Custom 2",
variables: [{ x: 10, y:20, z:30}]
},
]
},
{ level: "likely",
configs: [
{
config: "Custom 1",
variables: [{ x: 1, y:2, z:3}]
},
{
config: "Custom 2",
variables: [{ x: 10, y:20, z:30}]
},
]
}
]
},
]
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试更新集合以插入新的配置,如下所示:
newdata = {
config: …Run Code Online (Sandbox Code Playgroud) 是否可以将位置运算符'$'与深层嵌套文档数组上的查询结合使用?
考虑以下定义'user'的嵌套文档:
{
username: 'test',
kingdoms: [
{
buildings: [
{
type: 'castle'
},
{
type: 'treasury'
},
...
]
},
...
]
}
Run Code Online (Sandbox Code Playgroud)
我们希望为特定用户返回"城堡",例如:
{
kingdoms: [{
buildings: [{
type: 'castle'
}]
}]
}
Run Code Online (Sandbox Code Playgroud)
因为你不能两次使用$运算符(https://jira.mongodb.org/browse/server-831)我知道我也不能查询某个特定的王国,所以我正在尝试写一个查找语句第n个王国.
这在更新深度嵌套的子文档(Mongodb更新深层嵌套的子文档)时似乎有意义,但我在查找查询方面的成功较少.
我可以通过查询返回第一个王国的建筑物:
db.users.findOne(
{ username: 'test' },
{ kingdoms: {$slice: [0, 1]}, 'kingdom.buildings': 1 }
);
Run Code Online (Sandbox Code Playgroud)
但这会归还那个王国的所有建筑物.
按照位置运算符的单级示例,我正在尝试这样的查询:
db.users.findOne(
{ username: 'test', 'kingdoms.buildings.type': 'castle' },
{ kingdoms: {$slice: [n, 1]}, 'kingdom.buildings.$': 1 }
);
Run Code Online (Sandbox Code Playgroud)
以形式:
db.collection.find( { <array.field>: …Run Code Online (Sandbox Code Playgroud)