mongodbaggregation-framework

Mongodb Aggregation : Project an array without the first element


{
    "_id" : ObjectId("5e3179e83708dc0dcfefaf"),

    "CaseNumber" : "T978045628",

    "ServiceReferences" : [ 

        ObjectId("5e317d48bc13eaf17712a786"),

        ObjectId("5e317f0ec08d57f4a88c3444"),

        ObjectId("5e317f0ec08d57f4a88c3234")

    ]

}

I have a collection with above fields. I want to project the 'ServiceReferences' array except first element as I want to skip first indexed element of the array. Please help me. I have tried a couple of use cases like :

db.getCollection('cases').aggregate([{
             "$project": {

                  "ServRefs": { $pop: { ServiceReferences: -1 } }
              }
       },
       {
        $lookup: {

            from: 'services',

            localField: 'ServRefs',

            foreignField: '_id',

            as: 'serviceDoc'

        }
    }, { $unwind: '$serviceDoc' }])

Solution

  • Just try with this one

    db.getCollection('cases').aggregate([
    { $project: { ServiceReferences: 1, SerRef: { $slice: [ "$ServiceReferences", 1, {$subtract: [ {$size:"$ServiceReferences"}, 1 ]} ] }} }
    ])