【问题标题】:Retrieve Sub Document in Mongo在 Mongo 中检索子文档
【发布时间】:2016-03-21 03:09:00
【问题描述】:

我是 Mongo 的新手,正在努力检索特定文档的特定子文档

给定以下集合,我想检索"id" = 1 and "data.id" = 2 所在的内容。所以,我希望我的结果是“Java”对象。

{
    "id" : "1",
    "title" : "Section1",
    "data" : [ 
        {
            "id" : "1",
            "Product" : "Scala",
            "Description" : "",
        }, 
        {
            "id" : "2",
            "Product" : "Java",
            "Description" : "",
        }, 
        {
            "id" : "3",
            "Product" : "Ruby",
            "Description" : "",
        }, 
        {
            "id" : "4",
            "Product" : "HTML5",
            "Description" : "",
        }
        ]
}

{
    "id" : "2",
    "title" : "Section2",
    "data" : [ 
        {
            "id" : "4",
            "Product" : "Ansible",
            "Description" : "a free software platform for configuring and managing computers",
        }, 
        {
            "id" : "1",
            "Product" : "Chef",
            "Description" : "an open source configuration management tool",
        }, 
        {
            "id" : "2",
            "Product" : "Puppet",
            "Description" : "an open-source tool for managing the configuration of computer systems",
        }, 
        {
            "id" : "3",
            "Product" : "Saltstack",
            "Description" : "open source configuration management and remote execution application",
        }
   ]
}

我正在执行类似db.myCollection.find({$and : [{"id":"1"},{"data.id":"2"}]}) 的查询,但这会返回整个文档,其 id 为“1”,而不仅仅是我感兴趣的子文档。

我是在要求 Mongo 做一些它不适合做的事情,还是只是我的语法有问题?

【问题讨论】:

标签: mongodb


【解决方案1】:

也许这会有所帮助:

db.myCollection.find({"id":"1","data.id":"2"},{"id":1,"data.$":1})

不需要传递$and

【讨论】:

  • $ 是什么意思?谢谢!
  • 它将返回在data 中找到的匹配子文档,而不是返回整个data 数组
【解决方案2】:

您可以将 $match 与 $unwind 结合使用。这两个是聚合框架的一部分。

你的问题的答案是:

db.collection.aggregate([{$unwind:'$data'},{$match:{'data.Product':{$eq:'Java'}}}]);

参考:MongoDb unwind operator

【讨论】:

    【解决方案3】:

    您可以使用聚合框架。

    1. 检索具有匹配“数据”项的文档。

      db.getCollection('yourColl').aggregate([ {$unwind:"$data"}, {$match:{"id":"1", "data.id":"2"}}, {$group:{_id:"$_id", "id":{$first:"$id"}, "title":{$first:"$title"}, "data":{$push:"$data"}}} ])

    2. 如果你只想获取特定的子文档

      db.getCollection('yourColl').aggregate([ {$unwind:"$data"}, {$match:{"id":"1", "data.id":"2"}}, {$project:{_id:0, "id":"$data.id", "product":"$data.Product", "Description":"$data.Description"}} ])

    【讨论】:

      【解决方案4】:

      回答了我自己的问题:

      db.myCollection.find({$and : [{"id":"1"},{"data.id":"2"}]},{"data.$":1})

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-24
        • 1970-01-01
        相关资源
        最近更新 更多