为了账号安全,请及时绑定邮箱和手机立即绑定

如何在特定条件下使用猫鼬获得不同的对象?

如何在特定条件下使用猫鼬获得不同的对象?

慕标琳琳 2022-10-27 14:25:34
所以我的 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"}];...等等。我该如何做到这一点?
查看完整描述

1 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

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

.aggregate([

   {$match:{

      $or:[

           {city: regEx},

           {country: regEx},

           {region: regEx}

          ]

   }},

   {$group:{

      _id: {

             city: "$city",

             country: "$country"

           }

   }}

])


查看完整回答
反对 回复 2022-10-27
  • 1 回答
  • 0 关注
  • 59 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信