SirBT
SirBT

Reputation: 1698

How do I use the mongoDB Comparison Query Operator to check for values between createdAt dates?

I would like to view all the created users Meteor.users.find().fetch() that were created in the database between the beginning of 1st September and the end of 30th September. How do I achieve this in code.

Find inline my failed attempt:

var beginningOfMonth = new Date();
beginningOfMonth.setMonth(8, 1); 
console.log("beginning Of the Month: "+beginningOfMonth); 

The code above yeilds:

beginning Of the Month: Sat Sep 01 2018 21:44:00 GMT+0300 (East Africa Time)

...

var endOfMonth = new Date(); 
endOfMonth.setMonth(8, 30);     
console.log("end Of the Month: "+endOfMonth);

The code above yields:

end Of the Month: Sun Sep 30 2018 21:44:00 GMT+0300 (East Africa Time)

...perfect so far, however in the query below:

Meteor.users.find({ createdAt: { $gte: currentDate }}, { createdAt: { lte: endMonth }},  { "services.google.email": { $exists: true } } ).fetch();

The query above yields the below. NOTE that the createAt dates lay outside what the query queries.

[{…}]
 0:
  createdAt: Thu Oct 04 2018 14:54:33 GMT+0300 (East Africa Time) 
  profile: {name: "Sir ProgrammerAllot"}
  services: {google: {…}, resume: {…}}
  _id: "2trR7WxnqKJuuipG8"
  __proto__: Object
 length: 1
  __proto__: Array(0)

How do I modify the query to only show the users created in the database between 1st of september and the last day of September?

Looking forward to your response.

Upvotes: 0

Views: 65

Answers (2)

SirBT
SirBT

Reputation: 1698

Putting the "query terms into a single object" as suggested by @JohnnyHK, and wrapping every query (criteria) statement helped in making the overall query work.

Find below the working solution:

Meteor.users.find(
       {createdAt: { $gte: beginningOfMonth, $lte: endOfMonth }}, 
       {"services.google.email": { $exists: true }}
).count();

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311955

You need to put all your query terms into a single object (and use $lte instead of lte):

Meteor.users.find({
    createdAt: { $gte: currentDate, $lte: endMonth },
    "services.google.email": { $exists: true }
}).fetch();

Upvotes: 3

Related Questions