1

我想在我的 Web 应用程序中发表博客文章。最初我使用mysql作为数据库。在其中,我将在 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 中。请问有什么建议吗?

4

1 回答 1

1

使用 DBCollection 类的方法save是这样的:

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

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

    items.save(doc);
}

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

更新:

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

于 2010-11-30T19:40:06.487 回答