Reputation: 4074
I have the following mongodb query in node.js which gives me a list of unique zip codes with a count of how many times the zip code appears in the database.
collection.aggregate( [
{
$group: {
_id: "$Location.Zip",
count: { $sum: 1 }
}
},
{ $sort: { _id: 1 } },
{ $match: { count: { $gt: 1 } } }
], function ( lookupErr, lookupData ) {
if (lookupErr) {
res.send(lookupErr);
return;
}
res.send(lookupData.sort());
});
});
How can this query be modified to return one specific zip code? I've tried the condition clause but have not been able to get it to work.
Upvotes: 2
Views: 4750
Reputation: 301
if your trying to do this for an object id and your not getting any results, try using the mongoose.Types.ObjectId(id)
for example:
{
$match: {
userID: { $eq: new mongoose.Types.ObjectId(id) },
searchIndex: { $ne: -1 },
},
},
Upvotes: 0
Reputation: 4072
Aggregations that require filtered results can be done with the $match
operator. Without tweaking what you already have, I would suggest just sticking in a $match
for the zip code you want returned at the top of the aggregation list.
collection.aggregate( [
{
$match: {
zip: 47421
}
},
{
$group: {
...
This example will result in every aggregation operation after the $match
working on only the data set that is returned by the $match
of the zip
key to the value 47421
.
Upvotes: 2
Reputation: 903
in the $match pipeline operator add
{ $match: { count: { $gt: 1 },
_id : "10002" //replace 10002 with the zip code you want
}}
As a side note, you should put the $match operator first and in general as high in the aggregation chain as you can.
Upvotes: 0