首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >猫鼬MongoDB GeoSpatial查询

猫鼬MongoDB GeoSpatial查询
EN

Stack Overflow用户
提问于 2019-05-05 21:38:24
回答 1查看 870关注 0票数 1

我有一个Item集合,可以保存数千到几十万份文档。在该集合中,我想执行地理空间查询。使用Mongoose,有两个选项- find()和聚合管道。我已经展示了以下两种方法的实现:

猫鼬模型

首先,下面是“我的猫鼬模型”的相关属性:

代码语言:javascript
复制
// Define the schema
const itemSchema = new mongoose.Schema({
    // Firebase UID (in addition to the Mongo ObjectID)
    owner: {
        type: String,
        required: true,
        ref: 'User'
    },
    // ... Some more fields
    numberOfViews: {
        type: Number,
        required: true,
        default: 0
    },
    numberOfLikes: {
        type: Number,
        required: true, 
        default: 0
    },
    location: {
        type: {
            type: 'String',
            default: 'Point',
            required: true
        },
        coordinates: {
            type: [Number],
            required: true,
        },
    }
}, {
    timestamps: true
});

// 2dsphere index
itemSchema.index({ "location": "2dsphere" });

// Create the model
const Item = mongoose.model('Item', itemSchema);

查找查询

代码语言:javascript
复制
// These variables are populated based on URL Query Parameters.
const match = {};
const sort = {};

// Query to make.
const query = {
    location: {
        $near: {
            $maxDistance: parseInt(req.query.maxDistance),
            $geometry: {
                type: 'Point',
                coordinates: [parseInt(req.query.lng), parseInt(req.query.lat)]
            }
        }
    },
    ...match
};

// Pagination and Sorting
const options = {
    limit: parseInt(req.query.limit),
    skip: parseInt(req.query.skip),
    sort
};

const items = await Item.find(query, undefined, options).lean().exec();

res.send(items);

聚集管道

假设需要计算距离:

代码语言:javascript
复制
// These variables are populated based on URL Query Parameters.
const query = {};
const sort = {};

const geoSpatialQuery = {
    $geoNear: {
        near: { 
            type: 'Point', 
            coordinates: [parseInt(req.query.lng), parseInt(req.query.lat)] 
        },
        distanceField: "distance",
        maxDistance: parseInt(req.query.maxDistance),
        query,
        spherical: true
    }
};

const items = await Item.aggregate([
    geoSpatialQuery,
    { $limit: parseInt(req.query.limit) },
    { $skip: parseInt(req.query.skip) },
    { $sort: { distance: -1, ...sort } } 
]).exec();

res.send(items);

编辑-文档修改的示例

下面是一个文档的示例,它的所有属性都来自Item集合:

代码语言:javascript
复制
{
   "_id":"5cd08927c19d1dd118d39a2b",
   "imagePaths":{
      "standard":{
         "images":[
            "users/zbYmcwsGhcU3LwROLWa4eC0RRgG3/5cd08927c19d1dd118d39a2b/images/Image-aafe69c7-f93e-411e-b75d-319042068921-standard.jpg",
            "users/zbYmcwsGhcU3LwROLWa4eC0RRgG3/5cd08927c19d1dd118d39a2b/images/Image-397c95c6-fb10-4005-b511-692f991341fb-standard.jpg",
            "users/zbYmcwsGhcU3LwROLWa4eC0RRgG3/5cd08927c19d1dd118d39a2b/images/Image-e54db72e-7613-433d-8d9b-8d2347440204-standard.jpg",
            "users/zbYmcwsGhcU3LwROLWa4eC0RRgG3/5cd08927c19d1dd118d39a2b/images/Image-c767f54f-7d1e-4737-b0e7-c02ee5d8f1cf-standard.jpg"
         ],
         "profile":"users/zbYmcwsGhcU3LwROLWa4eC0RRgG3/5cd08927c19d1dd118d39a2b/images/Image-51318c32-38dc-44ac-aac3-c8cc46698cfa-standard-profile.jpg"
      },
      "thumbnail":"users/zbYmcwsGhcU3LwROLWa4eC0RRgG3/5cd08927c19d1dd118d39a2b/images/Image-51318c32-38dc-44ac-aac3-c8cc46698cfa-thumbnail.jpg",
      "medium":"users/zbYmcwsGhcU3LwROLWa4eC0RRgG3/5cd08927c19d1dd118d39a2b/images/Image-51318c32-38dc-44ac-aac3-c8cc46698cfa-medium.jpg"
   },
   "location":{
      "type":"Point",
      "coordinates":[
         -110.8571443,
         35.4586858
      ]
   },
   "numberOfViews":0,
   "numberOfLikes":0,
   "monetarySellingAmount":9000,
   "exchangeCategories":[
      "Math"
    ],
   "itemCategories":[
      "Sports"
   ],
   "title":"My title",
   "itemDescription":"A description",
   "exchangeRadius":10,
   "owner":"zbYmcwsGhcU3LwROLWa4eC0RRgG3",
   "reports":[],
   "createdAt":"2019-05-06T19:21:13.217Z",
   "updatedAt":"2019-05-06T19:21:13.217Z",
   "__v":0
}

问题

基于以上情况,我想问几个问题。

  1. 我对普通Mongoose查询的实现与使用聚合管道之间是否存在性能差异?
  2. 如果说neargeoNear在与GeoJSON一起使用2dsphere索引时与nearSphere非常相似,这是正确的吗?除了geoNear提供额外的数据和默认限制之外?也就是说,尽管有不同的单元,但这两个查询--概念上--都会显示来自某个位置的特定半径范围内的相关数据,尽管这个字段被称为radius ( nearSphere )和maxDistance (带有near/geoNear )。
  3. 使用上面的示例,如何减轻使用skip的性能损失,但仍然能够在查询和聚合中实现分页?
  4. find()函数允许一个可选参数来确定将返回哪些字段。聚合管道也需要一个$project阶段来完成。在流水线中是否应该使用$project来优化速度/效率,或者这不重要?

我希望按照堆栈溢出规则允许这种类型的问题。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2019-05-09 06:07:34

我用2dsphere索引尝试了下面的查询,我使用了聚合管道

对于下面的查询。

代码语言:javascript
复制
db.items.createIndex({location:"2dsphere"})

在使用聚合管道时,它为结果集提供了更大的灵活性。此外,聚合管道将提高运行地理相关搜索的性能。

代码语言:javascript
复制
db.items.aggregate([
{
 $geoNear: {
    near: { type: "Point", coordinates: [ -110.8571443 , 35.4586858 ] },
    key: "location",
    distanceField: "dist.calculated",
    minDistance: 2, 
    query: { "itemDescription": "A description" }
 }])

关于您在$skip上的问题,下面的问题将使您更深入地了解$skip oepration $skip and $limit in aggregation framework

您可以根据需要相应地使用$project。在我们的例子中,我们使用超过1,000万个数据的$project没有太多的性能问题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55996638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档