【问题标题】:MongoDB Query by Date And Sort by Distance (Mongoose + Express App)MongoDB 按日期查询和按距离排序(Mongoose + Express App)
【发布时间】:2017-10-11 14:05:58
【问题描述】:

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

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”,然后按该日期的事件与我的距离排序。任何建议将不胜感激谢谢;)

【问题讨论】:

    标签: javascript mongodb express mongoose


    【解决方案1】:

    使用$geoNear agg 管道运算符。它将返回文档按接近您指定的点的顺序。您可以使用调用中的query 选项告诉$geoNear 进一步将查找限制为您的start_time(或任何任意查询表达式)。详情在这里: https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/

    【讨论】:

    • 感谢这对于我的小例子来说有点复杂,我让它与 $and 运算符一起工作并稍微扭曲了“排序”。还是谢谢
    【解决方案2】:

    我设法让它与这个查询一起工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 2015-05-08
      • 2016-07-26
      • 2015-08-06
      • 2013-05-08
      相关资源
      最近更新 更多