Search code examples
node.jsmongodbmongooseprojection

Efficient way to reduce length of mongo array subdocuments on mongoose


I need a way to reduce the length of mongo subdocuments on mongoose.

I have a schema like this:

var schema = new Schema({
    field1: {
        type: String
    },
    subdocuments: {
        prop1: [{x:String,y:Number}],
        prop2: [{x:String,y:Number}]
    }
});

then I use a find from a model that uses this schema passing also the projection fields.

The problem is that prop1 and prop2 are very big arrays (around 1000 elements) so I need only the first n of those sorted by y.

Do you know an efficient way to get only the subdocuments I need?

Maybe it is better to use an aggregate function? And in this case how it works the projection to get only the fields I really need?

Many thanks in advance. d.


Solution

  • Please try to do it through aggregation, concate the prop1 array with prop2 array to prop array through $concatArrays, after unwinding the prop array, sort by y value, eventually $limit the first n element.

    var n = 6;
    Document.aggregate([
             {$project: {
                   prop: {$concatArrays: ['$sudocuments.prop1', 
                                          '$sudocuments.prop2']}}},
             {$unwind: '$prop'},
             {$sort: {'prop.y': 1}}, 
             {$limit: n}
      ])