mongodb - MongoDB查询多个嵌套字段的公共字段
问题描述
下面什么查询最好?我花了很多时间来解决这个问题,但没有得到成功。
(我最好补充一点清楚。我可以使用嵌套查询'fieldA.fieldB.fieldC':1,但是对于我的数据有很多'中间'字段。所以我不想全部列出,现在我想知道是否可以选择使用通配符作为 'fieldA.*.fieldC':1。)
数据:
{'name':'A', 'top': { 'middle_1': { 'bottom_1':'sdf', 'bottom_2':'1263'}, 'middle_2': {'bottom_1':'ttt', 'bottom_2':'6565'}}}
{'name':'B', 'top': { 'middle_1': { 'bottom_1':'ghh', 'bottom_2':'4448'}, 'middle_2': {'bottom_1':'gdg', 'bottom_2':'4535'}}}
{'name':'C', 'top': { 'middle_1': { 'bottom_1':'dfh', 'bottom_2':'7717'}, 'middle_2': {'bottom_1':'hewr', 'bottom_2':'2435'}}}
{'name':'D', 'top': { 'middle_1': { 'bottom_1':'tyr', 'bottom_2':'1211'}, 'middle_2': {'bottom_1':'oho', 'bottom_2':'4644'}}}
结果:
{'name':'A', 'top': { 'middle_1': { 'bottom_2':'1263'}, 'middle_2': {'bottom_2':'6565'}}}
{'name':'B', 'top': { 'middle_1': { 'bottom_2':'4448'}, 'middle_2': {'bottom_2':'4535'}}}
{'name':'C', 'top': { 'middle_1': { 'bottom_2':'7717'}, 'middle_2': {'bottom_2':'2435'}}}
{'name':'D', 'top': { 'middle_1': { 'bottom_2':'1211'}, 'middle_2': {'bottom_2':'4644'}}}
提前致谢!
解决方案
排除项目内部不需要的内容 find()
db.yourCollection.find({},
{
"top.middle_1.bottom_1": 0,
"top.middle_2.bottom_1": 0
})
如果要使用聚合,
db.yourCOllection.aggregate([
{
$project: {
"name": 1,
"top.middle_1.bottom_1": 1,
"top.middle_2.bottom_2": 1,
}
}
])
两者都是一样的。0
排除和1
包括参考$project
推荐阅读
- python - Python - 在没有根的情况下向 xml 添加新元素?
- amazon-web-services - 如何保持 WebSocket 连接活动 - Flutter AWS?
- laravel - 将主页重定向到经过身份验证的页面 Laravel 8 Jetstream Livewire [已解决]
- reactjs - 仅在登录用户满足特定条件时才显示按钮
- python - 模拟测试类中所有测试用例的导入方法
- javascript - 如何创建类以覆盖 JSON 蓝图 JS
- python - Python CSV 作为字典读入,第 n 行作为标题
- javascript - 如何检查每个表单值,并检查特定的复选框
- javascript - Go 调用 JavaScript 函数失败,因为在 JavaScript 代码中引入了缓冲区
- ruby-on-rails - 未初始化的常量 ActiveStorage::Analyzer::ImageAnalyzer::MiniMagick