开发者

How to store values in MONGO DB using JAVA?

I want to make a blog post in my web application. Initially I was using mysql as DB. In which i will get the post entered in the text area of blog as an object 开发者_运维技巧in JS and send that object to java server side. There I will write mysql query and get the object in resultset and save in database. But now i want to use mongoDB for the same. I am able to understand the basic stuff through many tutorials which I learnt. But I am unable to implement that in my application. I want to know how the object that comes from the JS will be sent inside the loop and how I should query to save the object also similarly if I need to send a object from server side to JS. How should i do.?

My Server side code:

    public DB MongoConnection(Blog blog) throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("myblog");
    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");

      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
     while(cursor.hasNext()){
        System.out.println(cursor.next());
    } 

In the above code i understood everything such as how a mongo connection, documents, collections and cursor's work. Now how should i save the value coming as an object from JS and save in mongoDB. Any Suggestions Please?


Use method save of DBCollection class something like that:

while(cursor.hasNext()){
    DBObject doc = cursor.next();

    doc.put("name", "Leo-vin");

    items.save(doc);
}

method cursor.next() returns object of type DBObject. It is your BSONObject.

Update:

to modify document (BSON) use method put of class BSONObject

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜