I am struggling with implementing Mongo DB in Java as a beginner. Despite going through several slides, I find myself confused about its functionality. When I tried running a small Java program using MongoDB, it didn't work as expected.
This is 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 displayed is: it continuously prints:
true true true true true true true true true true true true true true true true true true true true true true
As I am unable to figure out what is happening, I need assistance in inserting data into the collection "items". Also, if anybody can guide me on how to use MongoDB in Java, that would be greatly appreciated. Having a good understanding of MySQL, I'm finding it hard to transition my knowledge to MongoDB and understand queries like "query.put". Any suggestions?