SirBT
SirBT

Reputation: 1698

How do I use the $gte and $lte for dates in mongodb?

I have data in a collection. Each stored data was stored along with times indicating the times each data was inserted into the collection.

I have an issue formulating a query that shows data stored between the beginning of a specific month and the end of a specific month. Kindly help me with what is wrong with my query.

Find below the content of my collection.

Meteor.users.find({}).fetch(); 

(2) [{…}, {…}]
 0: {_id: "ZwT3hcmabytf82wyK", createdAt: Mon Dec 03 2018 11:16:53 GMT+0300 (East Africa Time)}
 1: {_id: "SEXZoHzt3ryKC2a4r", createdAt: Mon Dec 03 2018 11:16:34 GMT+0300 (East Africa Time)}
length: 2

Kindly note that the createdAt suggests the inserted data time, being: Monday 3rd December 2018 e.t.c.

And now note my query below. That beginningOfMonth variable and the endOfMonth variables are both set to the November month (beginningOfMonth.setMonth(10, 1) & endOfMonth.setMonth(10, 28)), and yet the results of the query is wrong:

var beginningOfMonth = new Date();
var endOfMonth = new Date();

beginningOfMonth.setMonth(10, 1);
endOfMonth.setMonth(10, 28);  

Meteor.users.find({}, { createdAt: { $gte: beginningOfMonth,  $lt: endOfMonth} }).fetch(); 

[{…}]
  0:{_id: "SEXZoHzt3ryKC2a4r", 
  createdAt: Mon Dec 03 2018 11:16:34 GMT+0300 (East Africa Time), 
  length: 1__proto__: Array(0)

Note that that the results of the query are wrong. The query seems to ignore the dates section createdAt: { $gte: beginningOfMonth, $lt: endOfMonth}.

Kindly help and show me what I am doing wrong.

Thanks in advance

Upvotes: 0

Views: 1674

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230386

show me what I am doing wrong.

You're not properly using meteor api. Pass your criteria as the first parameter.

Meteor.users.find({ createdAt: { $gte: beginningOfMonth,  $lt: endOfMonth} }).fetch(); 

Upvotes: 4

Related Questions