2011-09-28 79 views
1

如何使用10gen的C#驅動程序MongoDB的創建Geospatial Haystack IndexMongoDB的地理空間草堆索引

JS例:

db.foo.ensureIndex({ pos : "geoHaystack", type : 1 }, { bucketSize : 1 }) 

C#示例不起作用:

BsonDocument keys = new BsonDocument(); 
keys.Add("pos", "geoHaystack"); 
keys.Add("type", "1"); 

IMongoIndexKeys indexKeys = new IndexKeysDocument(keys); 

IndexOptionsDocument indexOptions = new IndexOptionsDocument("bucketSize", new BsonInt32(1)); 

collection.CreateIndex(indexKeys, indexOptions); 

給出了這樣的錯誤:

MongoDB.Driver.MongoSafeModeException : Safemode detected an error 'can only have 1 index plugin/bad index key pattern'. (Response was { "err" : "can only have 1 index plugin/bad index key pattern", "code" : 13007, "n" : 0, "connectionId" : 6, "ok" : 1.0 }).

所以,如果我刪除了 '類型' 鍵,就像這樣:

BsonDocument keys = new BsonDocument(); 
keys.Add("pos", "geoHaystack"); 

IMongoIndexKeys indexKeys = new IndexKeysDocument(keys); 

IndexOptionsDocument indexOptions = new IndexOptionsDocument("bucketSize", new BsonInt32(1)); 

collection.CreateIndex(indexKeys, indexOptions); 

我得到這個錯誤:

MongoDB.Driver.MongoSafeModeException : Safemode detected an error 'no other fields specified'. (Response was { "err" : "no other fields specified", "code" : 13317, "n" : 0, "connectionId" : 7, "ok" : 1.0 }).

回答

1

其實這個問題是指數的方向被指定爲一個字符串值

keys.Add("type", "1"); 

更改成整型

keys.Add("type", 1); 

這將按預期工作

+0

謝謝RameshVel :) – Robert

1

我得到了它的工作:

IMongoIndexKeys keys = new IndexKeysDocument { 
    { "Position", "geoHaystack" }, 
    { "type", 1 } 
}; 

IMongoIndexOptions options = new IndexOptionsDocument { 
    { "bucketSize", 1 } 
}; 

collection.EnsureIndex(keys, options); 

這個問題我與該數據庫中已經加載的數據有關。

然後,您應該能夠查詢:

var command = new CommandDocument { 
    { "geoSearch", "foo" }, 
    { "near", new BsonArray { 33, 33 } }, 
    { "maxDistance", 6 }, 
    { "search", new BsonDocument { { "type", "restaurant" } } }, 
    { "limit", 30 } 
}; 
database.RunCommand(command);