mongodb slice - 删除最后 n 个元素 [英] mongodb slice - remove last n elements

查看:54
本文介绍了mongodb slice - 删除最后 n 个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数组:

{
   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]
}

如何选择所有元素,除了最后 3 个?

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

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

我可以排除最后 3 个元素,但是我不能选择所有其他元素,因为如果 skip 为负数或 |skip|高于 list.length 然后它返回最后三个元素,好像 skip==0

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

如何选择所有元素,除了最后 3 个?

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

预期结果:

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

推荐答案

使用 MongoDb 聚合,我们可以使用 $size 运算符来计算数据长度:

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

注意:如果data可以为空,我们需要添加$max运算符

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

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

这篇关于mongodb slice - 删除最后 n 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆