mongodb slice - 删除最后 n 个元素 [英] mongodb slice - remove last n elements
问题描述
假设我有以下数组:
{
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 ]
}
]
}
}
}
])
注意:如果data
可以为空,我们需要添加$max
运算符
Note: If data
can be empty, we need to add $max
operator
{
$max: [
{
$subtract: [
{ $size: "$data" },
3
]
},
1
]
}
这篇关于mongodb slice - 删除最后 n 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!