MongoDB - How to $slice a sub-subarray

假如想象 提交于 2019-12-13 00:37:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!