【发布时间】: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