Panossa
Panossa

Reputation: 395

How do I get distinct objects with mongoose with specific conditions?

So I've got the following model in my Node.JS project:

const Activity = mongoose.Schema({
    name: {
        type: String,
        require: [true, "A activity must have a name"]
    },
    city: {
        type: String,
        require: [true, "A location must have a city"]
    },
    country: {
        type: String,
        require: [true, "A location must have a county"]
    },
}); 

(I omitted some attributes to make it easier, _id is generated by Mongo automatically)

What I now want to achieve is to get a list of all distinct locations. So basically in SQL: SELECT city,country FROM Activity WHERE city=regEx OR country=regEx;

What I tried so far:

let result = await Activity.find({$or: [{city: regEx}, {region: regEx}, {country: regEx}]}, "region city country -_id");
result = fastSet(result);

... where fastSet() is a function which removes duplicates. But now I want to do this in one query. What I found so far is that I can use aggregate() with $match (and $or inside), then maybe group and project but I guess I don't get the expected result if I use group here.

An example of the right result would be:

let result = [{city:"City A", country:"Country A"}, {city:"City B", country:"Country A"}, {city:"City C", country:"Country C"}];

...and so on. How do I achieve that?

Upvotes: 0

Views: 435

Answers (1)

Joe
Joe

Reputation: 28316

You would need 2 stages in an aggregation pipeline: $match to test the regular expressions, and $group with all of the fields you want to distinct inside the _id.

.aggregate([
   {$match:{
      $or:[
           {city: regEx},
           {country: regEx},
           {region: regEx}
          ]
   }},
   {$group:{
      _id: {
             city: "$city",
             country: "$country"
           }
   }}
])

Upvotes: 1

Related Questions