Mongodb Aggregation : Project an array without the last element

Viewed 2707

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

2 Answers

The shell query can be like this:

db.collection.aggregate([
    { $project: {
        doc1: 1,
        doc1_without_last: { $slice: [ 
            "$doc1", 
            { $subtract: [ { $size: "$doc1" }, 1 ] } 
        ] }
    } }
])

Docs:

If there are any limitations in spring that don't let you build such query, you may employ $let to use query variables:

db.collection.aggregate([
    { $project: {
        doc1: 1,
        doc1_without_last: { $let: {
            vars: { size: { $subtract: [ { $size: "$doc1" }, 1 ] } },
            in: { $slice: [ "$letters", "$$size"] }
        } }    
    } }
])

Finally, After Blowing my mind, the trick was simply that :

Aggregation agg = Aggregation.newAggregation(
Aggregation.project()
.andInclude("doc1","field1","field2")
.andExpression("slice(doc1, size(doc1)-1)").as("doc1_without_last"),
new OutOperation("newCollection")
                ).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());

the andExpression in projections serve to include some mongo operators in a String format.

Related