gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:03 27 4
gpt4 key购买 nike

我想在我的网络应用程序中发表博客文章。最初我使用 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 中。有什么建议吗?

最佳答案

使用方法save DBCollection 类的类似内容:

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

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

items.save(doc);
}

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

更新:

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

关于javascript - 如何使用JAVA在MONGODB中存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317614/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com