MongoDB:结合文本搜索和地理空间查询

标签 mongodb mongoose

我想知道是否可以结合文本搜索并对结果运行地理空间查询/我将如何做到这一点。我目前正在使用 Mongoose,但不介意直接使用 Mongo 作为命令。

我想要做的是允许用户搜索产品并返回特定位置内的结果。我有两个命令分别运行,但不知道如何组合它们。

最佳答案

Mongo DB 本身不支持文本和地理搜索。 Refer this

但是可以结合查询,可以达到结果

解决方案

  1. regex + near
const aggregate=YourCollection.aggregation()
aggregate.near({
    near:coord,
    includeLocs: "loc",
    distanceField: "distance",
    maxDistance: distance
});
aggregate.match({name:{$regex:keyword,$options: 'i'}})
aggregate.exec(function(err,yourDocuments){
    //your smart code
}) 
  1. Text search + regex

    var aggregate=YourCollection.aggregate();
    var match= {
      latitude: { $lt: yourCurrentLatitude+maxDistance, $gt: yourCurrentLatitude-maxDistance },
      longitude: { $lt: yourCurrentLongitude+maxDistance, $gt: yourCurrentLongitude-maxDistance },
      {$text:{$search:keyword}}
    };
    
    aggregate.match(match).exec(function(err,yourDocuments){//your smart code})
    
  2. Mapreduce + ( Text searchregex )

YourCollection.mapReduce(map, reduce, {out: {inline:1, query : yourFirstQuery}}, function(err, yourNewCollection) {
// Mapreduce returns the temporary collection with the results
    collection.find(yourNewQuery, function(err, result) {
      //your awsome code
    });
});

关于MongoDB:结合文本搜索和地理空间查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16883260/

相关文章:

node.js - 如何在 Node 应用程序中向所有关注者获取实时反馈

node.js - Mongoose 自动重新连接选项

具有不区分大小写的模式元素的 mongoDB 查询

javascript - 关于 mongoose 查询的 tailable cursor 的错误

node.js - Mongoose - 如何根据另一个字段更改 TTL?

javascript - 如何在子文档中填充模型实例数组? MongoDB Mongoose

mongodb - Play Framework 2.1 的最佳 mongodb 驱动程序

node.js - 使用 findOneAndRemove Mongoose 删除文档

mongodb如何在聚合查询中应用分页和照片总数

javascript - Mongoose TypeScript ObjectId 转换 - 类型 'string' 不可分配给类型 'Condition<ObjectId | undefined>'