问题
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