问题
Given a document like
{
data:{
'2015':['a', 'b', 'c', ...], //<array of n datapoints>
'2016':['d', 'e', 'f', ...], //<array of n datapoints>
},
someOtherField: {...}
}
I am trying to query a slice of one of the arrays within data
in the following way:
db.collection.find({}, {'data.2015':{'$slice': [3, 5]})
The query returns the entire data
field. Does that mean I can't $slice
a sub-subarray?
What would be the correct way to get a $slice
of the data.2015
array?
Solution
db.collection.find({}, {'data':0, 'someOtherField':0, 'data.2015':{'$slice': [3, 5]})
If someone knows how to elegantly suppress all other someOtherField
that would improve it
回答1:
$slice is returning an entire data field, but with a slices array.
I setup a similar environment to yours and this is what I got.
Without slice:
> db.collection.findOne({})
{
"_id" : ObjectId("584917b47778f75d3e0c96db"),
"data" : {
"2015" : [
1,
2,
3,
4,
5,
6,
7,
8
]
}
}
With slice:
> db.collection.findOne({}, {'data.2015' : {$slice: [0, 2]}})
{
"_id" : ObjectId("584917b47778f75d3e0c96db"),
"data" : {
"2015" : [
1,
2
]
}
}
It returns the entire data object, including other fields it might have, but the 2015 array is spliced from the 0 element plus 2.
If you only want the 2015 array from the data, you can do the following query:
> db.collection.find({}, {'data': 0, 'data.2015' : {$slice: [0, 2]}})
来源:https://stackoverflow.com/questions/41034708/mongodb-how-to-slice-a-sub-subarray