开发者

Mongo DB unknown Error?

开发者 https://www.devze.com 2023-01-27 08:53 出处:网络
I am new to Mongo DB I have to implement it in java. I went through may slides but I am confused what is happening. I executed a small java program using mongo DB but it is not working?

I am new to Mongo DB I have to implement it in java. I went through may slides but I am confused what is happening. I executed a small java program using mongo DB but it is not working?

My java c开发者_StackOverflowode:

    public class MongoDbTesting {

    public void connectingMongo() throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("todo");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items"); 
    System.out.println("items got");

    //to work with document we need basicDbObject       
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");
    //insert in mongo
    query.put("priority", "highest");
    items.insert(query);
    System.out.println("Inserted");     
      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
    //print highest priority items

    while(cursor.hasNext()){
        System.out.println(cursor.hasNext());
    }   
    } 
    }

The output is: it is getting printed continuously as

true true true true true true true true true true true true true true true true true true true true true true

I cant figure out what is happening. i want to insert some data into the collection "items" also if i want to know how to use Mongo in java. I know mysql well but shifting to mongo I cant relate both in queries. What is "query.put" is doing? Any suggestions please?


You got yourself an infinite loop because you forgot to call cursor.next() inside the while loop.


You have to use:

System.out.println(cursor.next());

rather than

System.out.println(cursor.hasNext());

...

0

精彩评论

暂无评论...
验证码 换一张
取 消