MongoDB lists - get every Nth item

前端 未结 6 2361
太阳男子
太阳男子 2021-02-13 05:36

I have a Mongodb schema that looks roughly like:

[
  {
    \"name\" : \"name1\",
    \"instances\" : [ 
      {
        \"value\" : 1,
        \"date\" : ISODate         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 06:07

    You can use below aggregation:

    db.col.aggregate([
        {
            $project: {
                instances: {
                    $map: {
                        input: { $range: [ 0, { $size: "$instances" }, N ] },
                        as: "index",
                        in: { $arrayElemAt: [ "$instances", "$$index" ] }
                    }
                }
            }
        }
    ])
    

    $range generates a list of indexes. Third parameter represents non-zero step. For N = 2 it will be [0,2,4,6...], for N = 3 it will return [0,3,6,9...] and so on. Then you can use $map to get correspinding items from instances array.

提交回复
热议问题