在MongoDB中,您是否可以拥有包含2dsphere(版本2)字段的非稀疏复合索引?

时间:2015-04-21 21:46:21

标签: node.js mongodb mongoose

假设我有

形式的文件
{
  _id: String,
  quality : String,
  loc: {
    type: String,
    coodinates: [Number]
  }
}

MongoDB文档说默认情况下2dsphere索引是稀疏的,但不清楚它们是否可以被强制为非稀疏。

我可以定义稀疏的复合索引{quality: 1, loc: '2dsphere'}吗?也就是说,我可以定义一个索引来搜索具有特定quality的文档,即使文档没有loc

我无法在MongoDB或Mongoose(我正在使用的ORM)的文档中找到任何内容。

1 个答案:

答案 0 :(得分:1)

TL; DR不幸 在Mongo Shell上检查/重现它:

use temp
db.places.insert({loc: {type: "Point", coordinates: [ -73.88, 40.78 ] }, name: "La Guardia Airport", category : "Airport" })
db.places.insert({loc: {type: "Point", coordinates: [-73.97, 40.77 ]}, name: "Central Park", category : "Parks"})
db.places.insert({name: "test no geo", category : "test"})
db.places.createIndex( { category:1, loc : "2dsphere"}, {sparse:false, name:'catsp'})
db.places.find({category:'Parks'}).hint('catsp')[0]
>>> { "_id" : ObjectId("5536d3e9d97d8ef614b8c1f6"), "loc" : { "type" : "Point", "coordinates" : [ -73.97, 40.77 ] }, "name" : "Central Park", "category" : "Parks" }
db.places.find({category:'test'}).hint('catsp')
>>> you will get NOTHING