Mongodb group by field using $ substr

I have a query to group by file name. Sort of

db.images.aggregate([ <query> ,        

             { $group: { _id: { $substr: [ "$FileName", 3, -1 ] }, files: { $push: "$$ROOT" } } },

             { $sort: { UploadDate : -1 } }
        ])

I need to set the starting index in the substring in order to first match the character "_". Something like that "$FileName.indexOf('_')". Can anyone help me?

+4
source share
1 answer

There is a dirty but working solution based on this link http://www.kamsky.org/stupid-tricks-with-mongodb/ugly-way-to-parse-a-string-with-aggregation-framework So why not and no?

, , . , indexOf.

function indexOf(field, character) {
    var array = [];
    var maxPos = 50;
    var searchStart = 0;

    array[maxPos]={"$cond":{"if":{"$eq":[{"$substr":[field,maxPos,1]},character]},"then":maxPos+1,else:0}};

    for ( var i=maxPos-1; i>searchStart-1; i-- ) {
         array[i]={"$cond":{"if":{"$eq":[{"$substr":[field,i,1]},character]},"then":i,"else":array[i+1]}}
    }

    return array[searchStart];
}

, MongoDB :

db.images.aggregate([ <query> ,
             { $group: { _id: { $substr: ["$FileName", indexOf("$FileName", "_"), 999] }, files: { $push: "$$ROOT" } } },
             { $sort: { UploadDate : -1 } }
        ])
0

All Articles