Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Mongoose, how to filter an array of objects

I have the following schema:

var sampleSchema = new Schema({
  name: String,
  dates: [{
    date: Date,
    duration: Number
  }]
});

I'd need to filters the records according to the following rule: if one of dates is later than a given date date_begin, keep the record, otherwise, don't.

I have the impression that $gte or $lte are the function I need, but I can't find a way to use them correctly. I tried

sampleSchema.find({date_begin: {$gte: 'date'}});

or some variants of that, but I can't seem to be able to make it work. Anyone has an idea of how I am supposed to do this?

like image 520
Stilltorik Avatar asked May 01 '13 20:05

Stilltorik


People also ask

How do I filter an array of objects in MongoDB?

Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

Can you filter an array?

Using filter() on an Array of Numbers The item argument is a reference to the current element in the array as filter() checks it against the condition . This is useful for accessing properties, in the case of objects. If the current item passes the condition , it gets returned to the new array.


1 Answers

To do querying on elements inside arrays, $elemMatch is used :

SampleModel.find( { dates : { $elemMatch: {  date : { $gte: 'DATE_VALUE' } } } } )

If you're using a single query condition, you can directly filter:

SampleModel.find( { 'dates.date': { $gte: 'DATE_VALUE' } } )
like image 97
DhruvPathak Avatar answered Sep 17 '22 00:09

DhruvPathak