从MongoDB发出检索子文档的问题

时间:2017-07-12 22:49:53

标签: mongodb mongodb-query

我有以下数据集:

{
    "_id" : ObjectId("59668a22734d1d48cf34de08"),
    "name" : "Nobody Cares",
    "menus" : [ 
        {
            "_id" : "menu_123",
            "name" : "Weekend Menu",
            "description" : "A menu for the weekend",
            "groups" : [ 
                {
                    "name" : "Spirits",
                    "has_mixers" : true,
                    "sizes" : [ 
                        "Single", 
                        "Double"
                    ],
                    "categories" : [ 
                        {
                            "name" : "Vodka",
                            "description" : "Maybe not necessary?",
                            "drinks" : [ 
                                {
                                    "_id" : "drink_123",
                                    "name" : "Absolut",
                                    "description" : "Fancy ass vodka",
                                    "sizes" : [ 
                                        {
                                            "_id" : "size_123",
                                            "size" : "Single",
                                            "price" : 300
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ],
            "mixers" : [ 
                {
                    "_id" : "mixer_1",
                    "name" : "Coca Cola",
                    "price" : 150
                }, 
                {
                    "_id" : "mixer_2",
                    "name" : "Lemonade",
                    "price" : 120
                }
            ]
        }
    ]
}

我尝试从该数据集中检索一杯饮料,我使用以下聚合查询:

db.getCollection('places').aggregate([
    { $match : {"menus.groups.categories.drinks._id" : "drink_123"} },
    { $unwind: "$menus" },
    { $project: { "_id": 1, "menus": { "groups": { "categories": { "drinks": { "name": 1 } } } }  } }
])

但是,它会返回数据集的完整结构以及正确的数据。

所以而不是:

{
  "_id": "drink_123",
  "name": "Absolut"
}

我明白了:

{
  "_id": ObjectId("59668a22734d1d48cf34de08"),
  "menus": {
    "groups": {
      "categories": {
        "drinks": { "name": "Absolut" } 
      }
    }
  }
}

例如。任何想法如何只检索子文档?

1 个答案:

答案 0 :(得分:0)

如果您需要保留深层嵌套模型,则此调用将生成所需的输出:

db.getCollection('places').aggregate([
    { $match : {"menus.groups.categories.drinks._id" : "drink_123"} },
    { $project: {"_id": '$menus.groups.categories.drinks._id', name: '$menus.groups.categories.drinks.name'}},
    { $unwind: "$name" },
    { $unwind: "$name" },
    { $unwind: "$name" },
    { $unwind: "$name" },
    { $unwind: "$_id" },
    { $unwind: "$_id" },
    { $unwind: "$_id" },
    { $unwind: "$_id" }
])

许多unwinds是drinks子文档深度嵌套的结果。

虽然,FWIW,这种查询可能暗示该模型不是“友好的”。