mongodb slice - remove last n elements

梦想与她 提交于 2021-02-11 17:46:17

问题


Supposing I have the following array:

{
   data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0]
}

How can I select all the elements, except the last 3 ?

Using db.find({},{ "_id": 0, "data": {'$slice': [-3, 3] }})

I can exclude the last 3 elements, however I cannot select all the others, because if skip is negative or |skip| is higher than list.length then it returns the last three elements as though skip==0

How can I select all the elements, except the last 3 ?

Desired outcome:

[1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0]

回答1:


With MongoDb aggregation, we can use $size operator to calculate data length:

db.collection.aggregate([
  {
    $project: {
      "_id": 0,
      "data": {
        "$slice": [ 
          "$data",
          0,
          {
            $subtract: [ { $size: "$data" }, 3 ]
          }
        ]
      }
    }
  }
])

MongoPlayground

Note: If data can be empty, we need to add $max operator

{
  $max: [
    {
      $subtract: [
        { $size: "$data" },
        3
      ]
    },
    1
  ]
}


来源:https://stackoverflow.com/questions/61046750/mongodb-slice-remove-last-n-elements

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