从mongodb中提取特定字段

时间:2014-08-14 06:21:20

标签: java json mongodb

我想在数据库 placementb 中检索表格位置中的地名。 我在数据库中的数据采用以下格式

 **{ "_id" : ObjectId("514c23udhgfhdfge"), "placeList" : "chennai,coimbatore,madurai........", "state" : "tamilnadu" }**

下面是我试过的代码,但它没有显示任何输出,我不知道出了什么问题

     MongoClient client = new MongoClient("localhost",27017); //with default server and port adress


     DB db = client.getDB("placedb");

     DBCollection areaColl=db.getCollection("places");

     DBCursor find=areaColl.find();

     String places = "";
     while(find.hasNext())
     {
         places=find.next().get("placeList").toString();                
     } 
     System.out.println(places);
     String[] place=places.split(",");
     for(int i=0;i<place.length;i++)
     {
         System.out.println(place[i]);
     }

2 个答案:

答案 0 :(得分:2)

这就是你的代码的样子:

MongoClient client = new MongoClient("localhost",27017); //with default server and port adress


     DB db = client.getDB("placedb");

     DBCollection areaColl=db.getCollection("places");


     BasicDBObject allQuery = new BasicDBObject();
     BasicDBObject fields = new BasicDBObject();
     fields.put("placeList", 1);
     DBCursor cursor = areaColl.find(allQuery, fields);

     String places = "";
     while(cursor.hasNext())
     {
         places=cursor.next().toString(); 
         System.out.println(places);               
     } 

     String[] place=places.split(",");
     for(int i=0;i<place.length;i++)
     {
         System.out.println(place[i]);
     }

答案 1 :(得分:0)

Chk this ............................................ < / p>

     MongoURI uri = new MongoURI("mongodb://ip of server");
    Mongo mongo = (new Mongo.Holder()).connect(uri);
    DB db = mongo.getDB("placeDB");
    DBCollection coll = db.getCollection("places");
    DBCursor cursor = coll.find();
    JSONArray placeList = new JSONArray();
    String places = "";
    while (cursor.hasNext()) {
        places = cursor.next().get("placeList").toString();

    }
    String[] place = places.split(",");
    for (int i = 0; i < place.length; i++) {
        placeList.add(place[i]);
    }

    System.out.println(placeList);