1

I am creating a collection in MongoDB in the following way and I want to create a 2dsphere index on location field of this collection from Java code. But I am not able to do so.

collection.ensureIndex() method expects a DBObject as a parameter but I cannot pass location to it.

How do I create collection.ensureIndex({"location" : "2dsphere"}) in Java code? MongoDB allows me to do so in command prompt. But, I want to index it through code written in 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])

2 Answers 2

3

ensureIndex() has been deprecated now. You should use createIndex() instead:

MongoClient mongoClient = new MongoClient();
DBCollection test = mongoClient.getDB("testdb").getCollection("test");
test.createIndex(new BasicDBObject("location","2dsphere"));
Sign up to request clarification or add additional context in comments.

1 Comment

can you please share the doc link saying deprecated?
2

You should construct a new DBObject that represents your index. See the code bellow:

DBObject index2d = BasicDBObjectBuilder.start("location", "2dsphere").get();
DBCollection collection = new Mongo().getDB("yourdb").getCollection("yourcollection");
collection.ensureIndex(index2d);

1 Comment

how do I use $near for the collection built with above structure of the document? I want to run a query from java which has $near in it. I tried QueryBuilder and BasicDbObject but could not find a right solution for it. Could you please help me on this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.