2013-07-03 3 views
1

다음과 같은 방법으로 MongoDB에 컬렉션을 만들고 있는데이 컬렉션의 위치 필드에 2dsphere 인덱스를 만들고 싶습니다. Java 코드입니다. 그러나 나는 그렇게 할 수 없다.Java에서 MongoDB 컬렉션 인덱싱

collection.ensureIndex() 메서드는 매개 변수로 DBObject이 필요하지만 위치를 전달할 수는 없습니다.

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

답변

2

색인을 나타내는 DBObject을 새로 만들어야합니다. 아래 코드를 참조하십시오 :

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

감사 미구엘 ..이 – koustubhC

+0

가 어떻게 문서의 위의 구조로 구축 된 수집을 위해 $ 근처 사용합니까 큰 일? $ 가까이있는 java에서 쿼리를 실행하고 싶습니다. QueryBuilder 및 BasicDbObject 시도했지만 올바른 솔루션을 찾을 수 없습니다. 이걸 좀 도와 주실 래요? – koustubhC

3

ensureIndex()은 현재 사용되지 않습니다. 대신 createIndex()를 사용해야합니다

MongoClient mongoClient = new MongoClient(); 
DBCollection test = mongoClient.getDB("testdb").getCollection("test"); 
test.createIndex(new BasicDBObject("location","2dsphere"));