yarons yarons - 1 year ago 93
Node.js Question

Querying array sub-document in mongoose

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?

Answer Source

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) { /* .... */ });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download