如何使用JAVA在MONGODB中存储值?

时间:2010-11-30 19:23:09

标签: javascript java mongodb mongo-java database

我想在我的网络应用程序中创建一个博客帖子。最初我使用 mysql 作为DB。其中我将在博客的文本区域中输入的帖子作为JS中的对象,并将该对象发送到Java服务器端。在那里,我将编写mysql查询和获取结果集中的对象并保存在数据库中。但现在我想使用mongoDB。通过我学到的许多教程,我能够理解基本的东西。但是我无法在我的应用程序中实现它。我想知道来自 JS 对象如何在循环中发送以及如何查询保存对象也类似,如果我需要从服务器端向JS发送一个对象。我该怎么办?

我的服务器端代码:

    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());
    } 

在上面的代码中我理解了一切,例如mongo连接,文档,集合和游标的工作方式。现在我应该如何保存来自JS的对象的值并保存在mongoDB中。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用DBCollection类的方法save

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

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

    items.save(doc);
}

方法cursor.next()返回DBObject类型的对象。这是你的BSONObject。

<强>更新

修改文件(BSON)使用类BSONObject的方法