Geospatial Indexing with a simple key first

心不动则不痛 提交于 2019-12-05 22:48:44

As you stated already Mongodb cannot accept location as secondary key in geo index. 2d has to be first in index. So you are out of luck here in changing indexing patterns here.

But there is a workaround, instead the compound geo index you can create two separate indexes on sid and one compound index with loc and sid

  db.your_collection.ensureIndex({sid : 1})
  db.your_collection.ensureIndex({loc : '2d',sid:1})

or two separate indexes on sid and loc

  db.your_collection.ensureIndex({sid : 1})
  db.your_collection.ensureIndex({loc : '2d'})

(am not sure which of the above one is efficient, you can try it yourself)

and you can make two different queries to get the results filterd by sid first and the location next, kinda like this

  res = db.your_collection.find({sid:10})
  //get all the ids from the res (res_ids)
  //and query by location using the ids
  db.your_collection.find({loc:{ $near : [50,50] } ,sid : {$in : res_ids}})  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!