首页 > 解决方案 > 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'}}}

提前致谢!

标签: mongodb

解决方案


排除项目内部不需要的内容 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


推荐阅读