I just started learning MongoDB and can't find a solution for my problem.
Got this document:
> db.test.insert({"name" : "Anika", "arr" : [ [11, 22],[33,44] ] })
Pay attention to the "arr" field, which is a multidimensional array.
Now I am looking for a query that returns only the value arr [0] [1], which is 22. I tried to achieve this using $ slice, however I do not know how to address the second dimension with this.
> db.test.find({},{_id:0,"arr":{$slice: [0,1]}}) { "name" : "ha", "arr" : [ [ 11, 22 ] ] }
I also tried
> db.test.find({},{_id:0,"arr":{$slice: [0,1][1,1]}}) { "name" : "ha", "arr" : [ [ 11, 22 ] ] }
The desired result will be either
22
or
{"arr":[[22]]}
thanks
EDIT:
After reading the comments, I think I have simplified the data of the example too much, and I must provide additional information:
- There are many more documents in the collection, such as I have provided. But they all have the same structure.
- There are more array elements than two
- In the real world, an array contains really long texts (500kb-1mb), so it’s very easy to transfer all the data to the client.
- Before aggregation, I will make a request on the 'name' field. Just skipped this in the example for simplicity.
- Target indices are variables, so sometimes I need to know the value of arr [0] [1], next time it is arr [1] [4]
data examples:
> 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] ] })
Request example:
> db.test.find({name:"Olivia"},{"arr:"...})