Search code examples
mongodbindexinggeospatialmongodb-javamongodb-indexes

Indexing MongoDB collection in Java


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])

Solution

  • 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);