Using aggregation pipeline in spring Data, I have documents with nested arrays, and I want to project an array except the last item of it. for example for each document like :
{
"_id" : ObjectId("59ce411c2708c97154d13150"),
"doc1" : [
{
"nodeValue" : "AAA"
},
{
"nodeValue" : "BBB"
},
{
"nodeValue" : "CCC"
},
{
"nodeValue" : "DDD"
}
],
"field2" : 20170102,
"field3" : 4,
}
I want as result :
{
"_id" : ObjectId("59ce411c2708c97154d13150"),
"doc1" : [
{
"nodeValue" : "AAA"
},
{
"nodeValue" : "BBB"
},
{
"nodeValue" : "CCC"
},
{
"nodeValue" : "DDD"
}
],
"doc1_without_last" : [
{
"nodeValue" : "AAA"
},
{
"nodeValue" : "BBB"
},
{
"nodeValue" : "CCC"
}
],
"field2" : 20170102,
"field3" : 4,
}
I tried something like this, but I didn't find a operator that can $pop the array and remove the last item from it.
Aggregation agg = Aggregation.newAggregation(
Aggregation.project()
.andInclude("doc1","field2","field3"),
Aggregation.project().and(ArrayOperators.arrayOf("doc1")..).as("doc1_without_last")
new OutOperation("newCollection")
).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
Thank you for your help
$slicethere.$slicejust controls the number of items of an array to project.$slice(-n)project just the last n elements and$slice(n)for the first n elements. But how to project all datas of the array except the last one.$size. All but the last is$slice($size - 1). Just in case docs.mongodb.com/manual/reference/operator/aggregation-array has all of them.$slicein java get only a numeric integer parameter. I had the idea to reverse the array to get simply the last one as the first like this.and(ArrayOperators.arrayOf(doc1).reverse()).as("Reversed_doc1) But how to exclude theReversed_doc1.0.nodeValuefrom the projection$size - 1, see stackoverflow.com/questions/39393672/… for inspiration