1

我正在MongoDB以下列方式创建一个集合,我想从代码中创建一个2dsphere关于该集合的位置字段的索引。Java但我不能这样做。

collection.ensureIndex()方法需要 aDBObject作为参数,但我无法将位置传递给它。

如何collection.ensureIndex({"location" : "2dsphere"})Java代码中创建? MongoDB允许我在命令提示符下这样做。但是,我想通过用 Java 编写的代码来索引它。

BasicDBObject doc = new BasicDBObject("attr1", nextLine[0])
                              .append("attr2", nextLine[1])
                              .append("edge-metro-code", nextLine[6])
                              .append("location", new BasicDBObject("type", "Point")
                                                            .append("coordinates",latLong)) 
                              .append("attr3", nextLine[9])
                              .append("attr4", nextLine[10])
4

2 回答 2

3

ensureIndex()现在已被弃用。您应该createIndex()改用:

MongoClient mongoClient = new MongoClient();
DBCollection test = mongoClient.getDB("testdb").getCollection("test");
test.createIndex(new BasicDBObject("location","2dsphere"));
于 2014-07-09T11:41:10.097 回答
2

您应该构造一个DBObject代表您的索引的新的。见下面的代码:

DBObject index2d = BasicDBObjectBuilder.start("location", "2dsphere").get();
DBCollection collection = new Mongo().getDB("yourdb").getCollection("yourcollection");
collection.ensureIndex(index2d);
于 2013-07-03T10:49:01.643 回答