我在为 mongoDB
的 mongoose 模式中尝试将对象插入多个嵌套数组时遇到问题。我有以下结构:
{
contries: [{
name: 'String',
states: [{
name: 'String',
cities: [{
name: 'String',
regions: [{
name: 'String',
habitants: [{
name: 'String',
age: Number
},
{
name: 'String',
age: Number
}
]
}]
}]
}]
}]
}
1 - 假设我想在特定城市的特定区域内插入居民等等,我该如何构建查询?
2 - 如果收到整个 json 对象作为请求,我需要检查国家、城市、州或地区是否存在,如果都不存在,我需要创建并插入居民在数组中。
3 - 如果我只需要从一个特定城市的一个特定区域获取居民数组,我如何使用投影运算符来过滤它? (我希望 mongo 过滤,而不是应用程序)。
4(奖励)- Habitants 数组仅包含居民对象的对象 Id,只需要使用填充?
最佳答案
用 mongodb 做这些事是不可能的。
根据 mongodb 文档,不可能遍历数组中超过 1 个部门。
The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value.
但是您可以使用其他架构,例如:
将 Habitant 文档置于顶层
这是居民文档:
{
name: 'hab1',
country: 'country1',
city: 'cit1',
region: 'region1'
}
使用此架构,您可以对数据进行规范化或反规范化,并且可以轻松查询和投影数据。
更新: 这个 mongodb 限制似乎在不久的将来解决 https://jira.mongodb.org/browse/SERVER-27089
关于javascript - 如何在 MongoDB 的多个嵌套数组中插入和查找对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45818249/