1

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I tried but its saying that i need to wait for 3 min to accept a answer. so only. sorry. 1 more min to go. please.
It's marked as an answer now, no need to apologize. I learned something new today - it takes a couple of minutes for an answer to get accepted, interesting.
yup yes. stackoverflow rocks. Please come often and help people like me. its been a great pride learning from you all. Thanks
1

You have to use:

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

rather than

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

...

1 Comment

+1 and if i have a option to mark both are right i will definitely do that but my hands are tied. sorry for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.