Reputation: 25552
I have an attribute in my collection called dateacquired
and the date is formatted like: 2014-03-28 06:08:00
.
I am needing to pull back all documents in my collection that are less than or equal to a month ago from the current date. I am just not sure how to write this query.
Anyone know how to start one something like this?
Upvotes: 6
Views: 4844
Reputation: 5108
My meteor method for how many people have signed up in the last nDays:
userCountPreviousDays: function (nDays) {
check(nDays, Number);
var arr = [];
var now = new Date().getTime();
var msInDay = 1000 * 60 * 60 * 24;
for (var i = 0; i < nDays; i++) {
arr[i] = Meteor.users.find({
createdAt: {
$lt: new Date(now - (msInDay * i)),
$gt: new Date(now - (msInDay * (i+1)))
}
}).count();
};
return arr;
}
arr[i]
is how many people signed up i
days ago.
Upvotes: 2
Reputation: 7366
I assume those dates are stored as strings? You can compare strings with the mongoDB comparison operators $gt
or $lt
and they work as you’d expect. I’m going to also use Sugar to make my life easier (highly recommended; add via mrt add sugarjs
) which gives me the Date.create
and Date.format
methods which reduce this into a one-liner:
var cursorOfDocumentsSinceOneMonthAgo = yourCollection.find({
dateacquired:
{ $gt: Date.create("1 month ago").format("{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}")
}
});
Upvotes: 2