【问题标题】:How do I get distinct objects with mongoose with specific conditions?如何在特定条件下使用猫鼬获得不同的对象?
【发布时间】:2020-07-03 10:38:55
【问题描述】:

所以我的 Node.JS 项目中有以下模型:

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"]
    },
}); 

(为了方便我省略了一些属性,_id是Mongo自动生成的)

我现在想要实现的是获取所有不同位置的列表。所以基本上在 SQL 中: SELECT city,country FROM Activity WHERE city=regEx OR country=regEx;

到目前为止我尝试了什么:

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

... 其中 fastSet() 是一个删除重复项的函数。但现在我想在一个查询中做到这一点。到目前为止,我发现我可以将 aggregate() 与 $match (和 $or 内部)一起使用,然后可能是 group 和 project 但我想如果我在这里使用 group ,我不会得到预期的结果。

正确结果的一个例子是:

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

...等等。 我该如何实现?

【问题讨论】:

  • let result = await Activity.find({$or: [{city: regEx}, {region: regEx}, {country: regEx}]}, "region city country -_id")。 sort({field : 1}).distinct('field');
  • 但是使用“distinct”我只能使用城市、地区或国家,对吧?到目前为止,这是我的问题

标签: javascript node.js mongodb mongoose


【解决方案1】:

聚合管道中需要 2 个阶段:$match 用于测试正则表达式,$group 包含您想要在 _id 中区分的所有字段。

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

【讨论】:

  • 好吧,我不认为你可以同时按两个属性分组。但是响应的格式不包括_id吗?我将如何摆脱它?使用项目()?
  • 是的,使用 $project 来重塑对象。
猜你喜欢
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2014-09-10
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 2020-02-22
相关资源
最近更新 更多