rohitpaniker
rohitpaniker

Reputation: 715

Find and return non duplicate values

I have a problem which I've been trying to solve since yesterday wherein I have written an API which accepts a city/subcity name and then queries database for all documents where city OR the subcity matches.

My problems is:

1) If there are 4 documents where 3 documents have city as Mumbai, 1 document has city as Navi Mumbai and when I query for Mumbai, I should get only 2 documents where one documents' city is Mumbai and another documents' city is Navi Mumbai but instead of working like that I get all 4 documents in return where I get 3 documents having city as Mumbai and 1 document having city as Navi Mumbai. I wanted to know how can I eliminate duplicate results and just return documents without duplicate keys and just one document of each without repeating key values

Currently my code looks like this:

exports.get_startup_based_on_locaton = function(req, res) {
    SSchema.find({ $or:[{'city': { $regex : new RegExp(req.params.location, "i")}}, {'subcity': { $regex : new RegExp(req.params.location, "i")}}]}, function(err, sschema) {
    if (err)
    res.send(err);
    res.json(sschema);
  })
}

Upvotes: 0

Views: 33

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151142

You want .aggregate() for this. It's the only thing that "groups", and .find() does not 'group`:

exports.get_startup_based_on_locaton = function(req, res) {
    SSchema.aggregate([
      { $match: { 
        $or:[
          {'city': { $regex : new RegExp(req.params.location, "i")}},
          {'subcity': { $regex : new RegExp(req.params.location, "i")}}
        ]
      }},
      { $project: { combined: ['$city','$subcity'] } },
      { $unwind: '$combined' },
      { $match: { combined: { $regex : new RegExp(req.params.location, "i")} } },
      { $group: { _id: '$combined' } }
    ], function(err, sschema) {
      if (err)
      res.send(err);
      res.json(sschema);
    })
}

After you search in both fields, you bring them together with $project from the documents that are matched. Then you $unwind the formed array and filter it for only the matching entries.

Finally $group emits the "unique" matched entries.

Upvotes: 1

Related Questions