【问题标题】:How can i access N th level of Sub Document in MongoDB如何访问 MongoDB 中的第 N 级子文档
【发布时间】:2018-07-17 18:32:19
【问题描述】:
{
"_id" : ObjectId("5b4d815ad85250f4e502d142"),
"company_Name" : "Rishabh Instruments",
"spaces" : [ 
    {
        "_id" : "11",
        "name" : "Trishala",
        "spaces" : [ 
            {
                "_id" : "111",
                "name" : "ESL"
            }, 
            {
                "_id" : "112",
                "name" : "IS"
            }
        ]
    }, 
    {
        "_id" : "12",
        "name" : "Riddhi",
        "spaces" : [ 
            {}
        ]
    }, 
    {
        "name" : "XYZ",
        "spaces" : [ 
            {}
        ]
    }
]

}

这是我在 Mongo DB 中的文档结构,它可能包含最高第 N 级的子文档,所以现在我想访问以 ESL 和 IS 命名的文档。那么我该怎么做才能通过以下查询升到第二级

    db.space.aggregate([
    {$match: {company_Name: 'Rishabh Instruments'}},
    {$unwind: '$spaces'},
    {$match: {'spaces.name': 'Trishala'}}
   // {$unwind: '$spaces'},
   // {$match: {'spaces.name': 'ESL'}}

])

但是如果我取消注释这两行,那么它不会返回任何东西 所以任何人都可以指导我或给出任何提示。

【问题讨论】:

标签: mongodb


【解决方案1】:

我尝试了以下解决方案,它按预期工作我可以通过链接键进入第 N 级,因为在我的情况下键是空格

db.space.aggregate([
    {$match: {company_Name: 'Rishabh Instruments'}},
    {$unwind: '$spaces'},
    {$match: {'spaces.name': 'Trishala'}},
    {$unwind: '$spaces.spaces'},
    {$match: {'spaces.spaces.name': 'ESL'}}

]) 

【讨论】:

    【解决方案2】:

    尝试使用投影的聚合查询以匹配您提供的示例输出:

    db.space.aggregate([
        {$match: {company_Name: 'Rishabh Instruments'}},
        {$unwind: '$spaces'},
        {$match: {'spaces.name': 'Trishala'}},
        {$unwind: '$spaces.spaces'},
        {$match: {$or : [{'spaces.spaces.name': 'ESL'},{'spaces.spaces.name': 'IS'}]}},
        {$project : {_id : 0, _id :'$spaces.spaces._id', name:'$spaces.spaces.name'}}
    ])
    

    输出:

    { "_id" : "111", "name" : "ESL" }
    { "_id" : "112", "name" : "IS" }
    

    【讨论】:

      猜你喜欢
      • 2013-11-08
      • 2016-11-02
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      相关资源
      最近更新 更多