MongoDB多维数组投影 [英] MongoDB multidimensional array projection
问题描述
我刚刚开始学习MongoDB,找不到解决我问题的方法.
I just started learning MongoDB and can't find a solution for my problem.
得到该文件:
> db.test.insert({"name" : "Anika", "arr" : [ [11, 22],[33,44] ] })
请注意"arr"字段,它是一个多维数组.
Please note the "arr" field which is a multidimensional array.
现在,我正在寻找一个仅返回arr [0] [1]的值(即22)的查询.我试图通过使用$ slice来实现这一点,但是我不知道如何解决第二维问题这样.
Now I'm looking for a query that returns only the value of arr[0][1] which is 22. I tried to achieve that by using $slice, however I don't know how to address the second dimension with that.
> db.test.find({},{_id:0,"arr":{$slice: [0,1]}})
{ "name" : "ha", "arr" : [ [ 11, 22 ] ] }
我也尝试过
> db.test.find({},{_id:0,"arr":{$slice: [0,1][1,1]}})
{ "name" : "ha", "arr" : [ [ 11, 22 ] ] }
所需的输出将是
22
或
{"arr":[[22]]}
谢谢
阅读评论后,我认为我已经简化了示例数据太多了,我必须提供更多信息:
After reading the comments I think that I've simplified the example data too much and I have to provide more information:
- 馆藏中还有更多类似的文件 我已经提供了.但是它们都具有相同的结构.
- 数组元素多于两个
- 在现实世界中,数组包含非常长的文本(500kb-1mb), 因此将整个数据传输到客户端非常昂贵.
- 在聚合之前,我将通过名称"字段进行查询.只是 为了简单起见,在示例中跳过了这一点.
- 目标索引是可变的,所以有时我需要知道 arr [0] [1]的值,下次是arr [1] [4]
- There are many more documents in the collection like that one that I've provided. But they all have the same structure.
- There are more array elements than just two
- In the real world the array contains really long texts (500kb-1mb), so it is very expansive to transmit the whole data to the client.
- Before the aggregation I will do a query by the 'name' field. Just skipped that in the example for the sake of simplicity.
- The target indexes are variable, so sometimes I need to know the value of arr[0][1], the next time it is arr[1][4]
示例数据:
example data:
> db.test.insert({"name" : "Olivia", "arr" : [ [11, 22, 33, 44],[55,66,77,88],[99] ] })
> db.test.insert({"name" : "Walter", "arr" : [ [11], [22, 33, 44],[55,66,77,88],[99] ] })
> db.test.insert({"name" : "Astrid", "arr" : [ [11, 22, 33, 44],[55,66],[77,88],[99] ] })
> db.test.insert({"name" : "Peter", "arr" : [ [11, 22, 33, 44],[55,66,77,88],[99] ] })
示例查询:
> db.test.find({name:"Olivia"},{"arr:"...})
推荐答案
您可以使用聚合框架:
db.test.aggregate([
{ $unwind: '$arr' },
{ $limit: 1 },
{ $project: { _id: 0, arr: 1 } },
{ $unwind: '$arr' },
{ $skip: 1 },
{ $limit: 1 }
])
返回:
{ "arr": 22 }
编辑:原始海报修改了我的解决方案以满足他的需要,并提出了以下建议:
The original poster has modified my solution to suit his needs and came up with the following:
db.test.aggregate([
{ $match: { name:"Olivia" } },
{ $project: { _id: 0,arr: 1 } },
{ $unwind: '$arr' },
{ $skip: 1 },
{ $limit:1 },
{ $unwind: "$arr" },
{ $skip: 2 },
{ $limit: 1 }
])
给定OP提供的扩展数据,此查询将导致{ arr: 77 }
.请注意,需要$ skip和$ limit来选择数组层次结构中的正确元素.
This query will result in { arr: 77 }
given the extended data provided by the OP. Note that $skip and $limit are needed to select the right elements in the array hierarchy.
这篇关于MongoDB多维数组投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!