【问题标题】:How to query mongo db with a nested model?如何使用嵌套模型查询 mongodb?
【发布时间】:2018-03-08 16:00:48
【问题描述】:

我在名为 Resources 的 mongodb 表中有类似于以下的数据。

{  
   "_id":"testuser",
   "_class":"com.Resources",
   "allocations":[  
      {  
         "contractId":"5083",
         "status":"UNKNOWN"
      }
   ]
}
{  
   "_id":"testuser",
   "_class":"com.Resources",
   "allocations":[  
      {  
         "contractId":"5084",
         "status":"Dead"
      }
   ]
}
{  
   "_id":"testuser2",
   "_class":"com.Resources",
   "allocations":[  
      {  
         "contractId":"5085",
         "status":"Live"
      }
   ]
}

我想在 shell 中运行一个查询,该查询返回每个 _id 的所有 contractID 及其状态,这实际上是我在表中的 resourceID。格式应为“_id - contractId - status”。例如,当使用上述数据运行时,我们应该看到以下内容:

testuser - 5083 - UNKNOWN
testuser - 5084 - Dead
testuser2 - 5085 - Live

感谢任何帮助。

【问题讨论】:

    标签: json database mongodb aggregate


    【解决方案1】:

    试试这个

    db.getCollection('Collection').find(/*Some Query*/).forEach(function(data){
        data.allocations.forEach(function(result){
            print(data._id + '-' + result.contractId + '-' + result.status); 
        })
    })
    

    【讨论】:

    • 由于某种原因,命令以 TypeError 结尾,表示 find(...).forEach(...) 未定义。不确定这是否意味着没有更多数据要检索,或者它正在停止中间查询并出现错误
    • 您使用的是哪个 mongo 版本?
    • 我使用的是 3.4.0 版本。我还在查询末尾添加了一个 .toArray(),这样我就可以在我的 shell 中获取整个转储,以便将所有内容复制到剪贴板以进行后期处理。
    • 它也可以在 3.4.0 中使用,但执行以上面提到的 TypeError 结束。我不相信我错过了任何数据,但在想为什么它最后会出错。
    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2012-05-04
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多