MongoDB按日期查询并按距离排序(Mongoose+Express应用程序)



我正在构建一个事件应用程序,希望在某个日期获取所有事件,然后按位置对它们进行排序。如何实现这样的请求?这就是架构的样子:

var eventSchema = mongoose.Schema({
_id: {
type: String,
required: true
},
name: {
type: String,
required: true
},
start_time: {
type: Date
},
location: {
type: {
type: String
},
coordinates: []
},
});

我知道我可以使用$near查询位置,我已经成功运行了。但我想先查询"start_time",然后根据当天发生的事件与我的距离进行排序。如果有任何建议,我们将不胜感激,谢谢;)

使用$geoNearagg管道运算符。它将按接近指定点的顺序返回文档。您可以告诉$geoNear使用调用中的query选项将查找进一步约束为仅您的start_time(或任何任意查询表达式)。此处提供详细信息:https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/

我设法让它处理这个查询:

{
location: {
$near : {
$geometry: { type: "Point",  coordinates: [longitude,latitude] 
},
$maxDistance: 10000
}
},
$and: [
{ start_time : {$gte: now, $lt: tomorrow} }
]
}

最新更新