【问题标题】:Querying nested documents in JSON using MongoDB使用 MongoDB 在 JSON 中查询嵌套文档
【发布时间】:2015-12-24 05:17:59
【问题描述】:

所以我想使用 Node.js 驱动程序来查询一组JSON 数据。我已经看到所有使用点符号的帖子,以及所有这些,但我没有得到任何结果。下面是我正在使用的数据的示例JSON。我正在尝试查询 Arsenal 参与的所有匹配项。我无处可去,因为我不太确定如何查询 team1team2 下的名称(例如仅当阿森纳位于team1team2 时才会显示文件。我以为team1team2应该是一个数组,这样会更容易,但这是一个非常大的文档,我无法控制,所以我不想改变结构。

{
    "_id" : ObjectId("56773d88a09bc70f31a900d5"),
    "name" : "English Premier League 2012/13",
    "rounds" : [ 
        {
            "name" : "Matchday 1",
            "matches" : [ 
                {
                    "date" : "2012-08-18",
                    "team1" : {
                        "key" : "arsenal",
                        "name" : "Arsenal",
                        "code" : "ARS"
                    },
                    "team2" : {
                        "key" : "sunderland",
                        "name" : "Sunderland",
                        "code" : "SUN"
                    },
                    "score1" : 0,
                    "score2" : 0
                }, 
                {
                    "date" : "2012-08-18",
                    "team1" : {
                        "key" : "fulham",
                        "name" : "Fulham",
                        "code" : "FUL"
                    },
                    "team2" : {
                        "key" : "norwich",
                        "name" : "Norwich",
                        "code" : "NOR"
                    },
                    "score1" : 5,
                    "score2" : 0
                }
            ]
        }
    ]
}

【问题讨论】:

    标签: javascript json mongodb documents


    【解决方案1】:

    您可以使用$elemMatch 查询数组内部:

    db.getCollection('test').find({
        rounds: { $elemMatch: {
            $or: [
                { matches: { $elemMatch: { "team1.code": "ARS" } } },
                { matches: { $elemMatch: { "team2.code": "ARS" } } }
            ]
        } }
    });
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      db.sample.aggregate(
          {$match: '...'}
          { $unwind: '$rounds'},
          { $unwind: '$rounds.matches'},
          { $match: {'rounds.matches.team1.name': 'Arsenal'}},
          { $group: '...'}
      )
      

      【讨论】:

        猜你喜欢
        • 2018-03-09
        • 2021-02-25
        • 2016-08-16
        • 2019-11-11
        • 2015-02-10
        • 2012-10-17
        • 2016-05-07
        • 1970-01-01
        相关资源
        最近更新 更多