Reputation: 1372
I am trying to make a group query on mongodb (using mongoose) filtering by any other different field than the group criteria. I have this by the moment:
usersDB.aggregate().group (
{_id: '$residence', total: { $sum: 1 } }
).exec(function (err, result) {
if(err) res.send(err);
else res.send(result);
});
And it works... it shows me for example:
[{"_id":"Javea","total":40},{"_id":"Benissa","total":28},{"_id":"Calpe","total":41},{"_id":"Teulada","total":14}]
But now, what I want to do is filtering too by date of last visit (last_visit is other field of UsersDB). I tried this:
usersDB.find({$and:[{last_visit:{$lt:date}}, {last_visit:{$gt:date.setMonth(3)}}]}).aggregate().group(
{_id: '$residence', total: { $sum: 1 } }).exec(
function (err, result) {
if(err) res.send(err);
else res.send(result);
});
And of course... it doesn't work!!
Any suggestion?
Upvotes: 1
Views: 11733
Reputation: 41
in mongo shell, it look's like:
db.users.aggregate([
{ $match : { $and [{last_visit:{$lt:date}}, {last_visit:{$gt:date.setMonth(3)}}]}},
{ $group : { _id: '$residence', total: { $sum: 1 } }}
]);
Upvotes: 4
Reputation: 103435
You need to do the filtering within the aggregation pipeline using the $match
operator stage:
var start = date, end = date;
end.setMonth(3);
var query = { "last_visit": { "$lt": end, "$gt": start } };
usersDB.aggregate()
.match(query)
.group({"_id": "$residence", "total": { "$sum": 1 } })
.exec(function (err, result) {
if(err) res.send(err);
else res.send(result);
});
Upvotes: 4