从MongoDB检索子文档时出现问题
我有以下数据集:从MongoDB检索子文档时出现问题,mongodb,mongodb-query,Mongodb,Mongodb Query,我有以下数据集: { "_id" : ObjectId("59668a22734d1d48cf34de08"), "name" : "Nobody Cares", "menus" : [ { "_id" : "menu_123", "name" : "Weekend Menu", "description" : "A menu for the weekend",
{
"_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" }
}
}
}
}
比如说。你知道如何检索子文档吗 如果需要保留深度嵌套的模型,则此调用将生成所需的输出:
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" }
])
大量展开是子文档深度嵌套的结果
尽管如此,FWIW,这种查询可能确实表明该模型不是“可读的”。如果需要保留深度嵌套的模型,则此调用将生成所需的输出:
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" }
])
大量展开是子文档深度嵌套的结果
不过,FWIW,这种查询可能确实表明该模型不“可读”。展平阵列。你在这里试图做的事情并没有给你带来你似乎认为它能带来的好处。事实上,它使查询和更新变得更糟糕。因此,您的“嵌套”实际上在这里更好地反映为单个元素数组的“属性”。这很容易更新和查询,而不是这里真正不可行的表单。你似乎被误导了,认为“组”和“类别”在这种形式下对你有用。事实并非如此。作为“属性”,但是“它将是有用的”,但目前这对性能或原子更新不好。展平阵列。你在这里试图做的事情并没有给你带来你似乎认为它能带来的好处。事实上,它使查询和更新变得更糟糕。因此,您的“嵌套”实际上在这里更好地反映为单个元素数组的“属性”。这很容易更新和查询,而不是这里真正不可行的表单。你似乎被误导了,认为“组”和“类别”在这种形式下对你有用。事实并非如此。作为“属性”,但是“它会很有用”,但目前这对性能或原子更新不好。请查看$map操作符: