如何查询深度嵌套的json文档? [英] How to QUERY a deeply nested json document?

查看:135
本文介绍了如何查询深度嵌套的json文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将一个巨大的json文件导入mongoDB.它已导入为一个完整的文档(带有一个_id).我的json看起来像这样:

I have imported a huge json file into mongoDB. It has imported as one whole document (with one _id). My json looks like this:

       {
  "_id": ObjectId("bas8adsfa832034821"),
  "Spele": {
    "Laiks": "2017/01/11",
    "Skatitaji": 6740,
    "Vieta": "Newlands Stadium",
    "T": [
      {
        "Uzvards": "Antamo",
        "Vards": "Dennis"
      },
      {
        "Uzvards": "Prompa",
        "Vards": "Pedro"
      }
    ],
    "Komanda": [
      {
        "Nosaukums": "Barcelona",
        "Speletaji": {
          "Speletajs": [
            {
              "Loma": "V",
              "Nr": 16,
              "Uzvards": "Sam",
              "Vards": "Sidney"
            },
            {
              "Loma": "A",
              "Nr": 17,
              "Uzvards": "Cisovsky",
              "Vards": "Marian"
            }
          ]
        }
      }
    ]
  }
}

因此,我尝试执行的每个查询都会返回整个文档.设置特定参数无济于事:db.games.find({"Spele.Komanda.Speletaji.Speletajs.Nr" : 16})

So with every query I try, it returns the whole document. Setting specific parameters don't help like: db.games.find({"Spele.Komanda.Speletaji.Speletajs.Nr" : 16})

我希望它会返回

{ "Loma" : "V",
   "Nr" : 16,
   "Uzvards" : "Sam"
   "Vards" : ""Sidney"
}

但是它返回整个文档.也许我没有正确使用查询,或者我必须为每个嵌套文档提供_id,但是我不知道如何.我可以使用mongo shell或PHP来做到这一点.

But it returns the whole document instead. Maybe I'm not using the query right, or I have to provide every nested document with _id, but I don't know how. I can use mongo shell or PHP to do this.

推荐答案

您可以在下面的汇总查询中进行尝试.

You can try below aggregation query.

$filter内部数组和$arrayElemAt来投影匹配的元素.

$filter inner array and $arrayElemAt to project the matched element.

$map可在所有Kamadas中输出所有匹配的Speletajs元素.

$map to output all matching Speletajs elements across all Kamadas.

$arrayElemAt减少为单个匹配项.对于多个匹配项,请删除$arrayElemAt.

$arrayElemAt to reduce to a single match. For multiple matches remove $arrayElemAt.

db.games.aggregate([
  {"$match":{"Spele.Komanda.Speletaji.Speletajs.Nr":16}},
  {"$project":{
    "Speletaji":{
      "$arrayElemAt":[
        {"$map":{
          "input":"$Spele.Komanda",
          "in":{
            "$arrayElemAt":[
              {"$filter":{
                "input":"$$this.Speletaji.Speletajs",
                "cond":{"$eq":["$$this.Nr",16]}

              }},
            0]
          }
        }},
      0]
    }
  }}
])

这篇关于如何查询深度嵌套的json文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆