简体   繁体   中英

Mongo DB unknown Error?

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 code:

    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?

您陷入了无限循环,因为您忘记了在while循环内调用cursor.next()。

You have to use:

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

rather than

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

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM