0

I'm using MongoDB in a Node.js app with mongoose. I have a collection in my DB, that can be described with the following schema:

{
  id: String,
  name: String,
  indicators: [{
    date: Date,
    value: Number
  }]
}

where id is unique, and each document has a lot of indicators in it.

I want to able to query the collection according to attributes of the indicators array. For example: sort the array by date or limit the amount of results in the array (possibly with an offset).

How can I do that?

1 Answer 1

1

You can limit the number of items in the array with $slice. For example:

Model.find({}, { indicators: { $slice: 5 } }, function(err, data) {
    // ...
});

Will return the first 5 elements.

But if you want to sort it, then you will have to use the aggregation framework:

Model.aggregate([
    { $unwind: '$indicators' },
    { $sort: { 'indicators.date': -1 } }
], function(err, data) { /* .... */ });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.