2

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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 },
        },
      },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.