在本文中,我们将详细介绍如何使用mongo-go-driver有效地将bson转换为json?的各个方面,并为您提供关于mongodbdocument转json的相关解答,同时,我们也将为您带来关于M
在本文中,我们将详细介绍如何使用mongo-go-driver有效地将bson转换为json?的各个方面,并为您提供关于mongodb document转json的相关解答,同时,我们也将为您带来关于Mongo 如何将 ISO 日期转换为 BSON 时间戳值、mongodb-go-driver / bson结构转换为bson.Document编码、tio-boot使用mongo-java-driver操作mongodb、事件中心将JSON转换为JSON字符串的有用知识。
本文目录一览:- 如何使用mongo-go-driver有效地将bson转换为json?(mongodb document转json)
- Mongo 如何将 ISO 日期转换为 BSON 时间戳值
- mongodb-go-driver / bson结构转换为bson.Document编码
- tio-boot使用mongo-java-driver操作mongodb
- 事件中心将JSON转换为JSON字符串
如何使用mongo-go-driver有效地将bson转换为json?(mongodb document转json)
我想将mongo-go-driver中的
bson转换为json。
我应该小心处理NaN
,因为json.Marshal
如果NaN
数据中存在则失败。
例如,我想将以下bson数据转换为json。
b, _ := bson.Marshal(bson.M{"a": []interface{}{math.NaN(), 0, 1}})// How to convert b to json?
以下失败。
// decodevar decodedBson bson.Mbson.Unmarshal(b, &decodedBson)_, err := json.Marshal(decodedBson)if err != nil { panic(err) // it will be invoked // panic: json: unsupported value: NaN}
答案1
小编典典如果您知道BSON的结构,则可以创建一个实现json.Marshaler
和json.Unmarshaler
接口的自定义类型,并根据需要处理NaN。例:
type maybeNaN struct{ isNan bool number float64}func (n maybeNaN) MarshalJSON() ([]byte, error) { if n.isNan { return []byte("null"), nil // Or whatever you want here } return json.Marshal(n.number)}func (n *maybeNan) UnmarshalJSON(p []byte) error { if string(p) == "NaN" { n.isNan = true return nil } return json.Unmarshal(p, &n.number)}type myStruct struct { someNumber maybeNaN `json:"someNumber" bson:"someNumber"` /* ... */}
如果您的BSON具有任意结构,则唯一的选择是使用反射遍历该结构,并将所有出现的NaN转换为类型(可能是如上所述的自定义类型)
Mongo 如何将 ISO 日期转换为 BSON 时间戳值
如何解决Mongo 如何将 ISO 日期转换为 BSON 时间戳值?
在 Mongodb 中,如果我的 ISODate 为“2021-07-29T01:57:49.075Z”,我该如何将此值转换为等效的 BSON 时间戳值? BSON 值应采用 Timestamp(nnnnnnnnnn,1) 的形式。 n 值的长度为 10 位。我已经看到使用 $toLong 聚合的接近答案,但返回的长数字不适合 10 位数字。 反之亦然,如何将 BSON 时间戳值转换为 ISODate。
这看起来很简单,但我找不到任何参考资料,类似的问题转换为长数字,而不是上述形式的 BSON 时间戳。 感谢您的帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
mongodb-go-driver / bson结构转换为bson.Document编码
我正在使用https://github.com/mongodb/mongo-go-
driver,目前正在尝试实现这种结构的部分更新
type NoteUpdate struct {
ID string `json:"id,omitempty" bson:"_id,omitempty"`
Title string `json:"title" bson:"title,omitempty"`
Content string `json:"content" bson:"content,omitempty"`
ChangedAt int64 `json:"changed_at" bson:"changed_at"`
}
例如,如果我有
noteUpdate := NoteUpdate{ Title: "New Title" }
然后,我希望存储文档中唯一的“标题”字段将被更改。
我需要写类似
collection.FindOneAndUpdate(context.Background(),bson.NewDocument(bson.EC.String("_id",noteUpdate.ID)),// I need to encode non-empty fields here
bson.NewDocument(bson.EC.SubDocument("$set",bson.NewDocument(...)))
)
问题是我不想用bson.EC.String(...)
或手动编码每个非空字段bson.EC.Int64(...)
。我尝试使用bson.EC.InterfaceErr(...)
但出现错误
无法为* models.NoteUpdate类型创建元素,请尝试使用bsoncodec.ConstructElementErr
不幸的是,bsoncodec中没有这样的功能。我发现的唯一方法是创建包装器
type SetWrapper struct {
Set interface{} `bson:"$set,omitempty"`
}
并像这样使用
partialUpdate := &NoteUpdate{
ID: "some-note-id",Title: "Some new title",}
updateParam := SetWrapper{Set: partialUpdate}
collection.FindOneAndUpdate(
context.Background(),updateParam,)
它可以工作,但是使用bson / bsoncodec文档构建器是否可以实现相同的目的?
UPD。我的问题的全部内容:我编写了REST端点,用于 部分 更新“注释”文档(存储在MongoDB中)。我现在拥有的代码:
var noteUpdate models.NoteUpdate
ctx.BindJSON(¬eUpdate)
//omit validation and errors handling
updateParams := services.SetWrapper{Set: noteUpdate}
res := collection.FindOneAndUpdate(
context.Background(),updateParams,findopt.OptReturnDocument(option.After),)
我想要的代码
var noteUpdate models.NoteUpdate
ctx.BindJSON(¬eUpdate)
//omit validation and errors handling
res := collection.FindOneAndUpdate(
context.Background(),bson.NewDocument(
//bsoncodec.ConstructElement doesn't exists
bsoncodec.ConstructElement("$set",¬eUpdate)),),)
代码,我 不 希望有
var noteUpdate models.NoteUpdate
ctx.BindJSON(¬eUpdate)
//omit validation and errors handling
bsonNote := bson.NewDocument()
if noteUpdate.Title != "" {
bsonNote.Append(bson.EC.String("title",noteUpdate.Title))
}
if noteUpdate.Content != "" {
bsonNote.Append(bson.EC.String("content",noteUpdate.Content))
}
//..setting the rest of the fields...
res := collection.FindOneAndUpdate(
context.Background(),bson.NewDocument(bson.EC.SubDocument("$set",bsonNote)),)
因此,确切的问题是-是否有任何方法可以基于bson
标签动态构建* bson.Document (没有像我的SetWrapper这样的预定义包装器)?
tio-boot使用mongo-java-driver操作mongodb
tio-boot使用mongo-java-driver操作mongodb
在这个示例中,创建了一个使用MongoDB的简单Java Web应用程序。这个应用程序包括了数据库依赖配置、数据库操作工具类、配置类、控制器类以及实际的HTTP请求处理。下面我将详细解释每一部分的作用和逻辑。
- MongoDB Java Driver 依赖
MongoDB Java Driver,这是一个为Java应用程序提供的MongoDB官方驱动程序。
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.1.0</version>
</dependency>
- MongoDb 工具类
- 这个类作为MongoDB的客户端和数据库对象的容器。它提供静态方法来存取这些对象,确保你的应用程序可以在需要时连接到数据库。
getDatabase(String databaseName)
: 连接到指定名称的数据库。getDatabase()
: 获取已经配置好的数据库实例。setClient(MongoClient mongoClient)
: 设置MongoDB的客户端实例。setDatabase(MongoDatabase mongoDatabase)
: 设置MongoDB的数据库实例。
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDb {
private static MongoClient mongoClient;
private static MongoDatabase mongoDatabase;
public static MongoDatabase getDatabase(String databaseName) {
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
return mongoDatabase;
}
public static MongoDatabase getDatabase() {
return mongoDatabase;
}
public static void setClient(MongoClient mongoClient) {
MongoDb.mongoClient = mongoClient;
}
public static void setDatabase(MongoDatabase mongoDatabase) {
MongoDb.mongoDatabase = mongoDatabase;
}
}
- MongoClientConfiguration 配置类
- 这个类是你应用程序的配置类,它负责设置和初始化MongoDB客户端。
- 它创建了数据库的地址和凭证,并用这些信息初始化了MongoClient。
- 然后它使用MongoClient来连接到数据库,并将这个连接保存在MongoDb工具类中,以便全局使用。
- 最后,它向
TioBootServer
添加了一个销毁方法,以确保在应用程序关闭时MongoClient也会被正确关闭。
package com.litongjava.tio.web.hello.config;
import java.util.ArrayList;
import java.util.List;
import com.litongjava.jfinal.aop.annotation.AConfiguration;
import com.litongjava.jfinal.aop.annotation.AInitialization;
import com.litongjava.tio.boot.server.TioBootServer;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
@AConfiguration
public class MongoClientConfiguration {
@AInitialization
public void config() {
String mongodbHost = "192.168.3.9";
int mongodbPort = 27017;
String mongodbSourceName = "admin";
String mongodbUsername = "admin";
String mongodbPassword = "Litong@123";
List<ServerAddress> adds = new ArrayList<>();
// ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress(mongodbHost, mongodbPort);
adds.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<>();
// MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(mongodbUsername, mongodbSourceName,
mongodbPassword.toCharArray());
credentials.add(mongoCredential);
// 通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(adds, credentials);
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(mongodbSourceName);
// 保持client and database;
MongoDb.setClient(mongoClient);
MongoDb.setDatabase(mongoDatabase);
// 添加addDestroyMethod
TioBootServer.addDestroyMethod(mongoClient::close);
}
}
- MongdbController 控制器类
- 这个类处理实际的HTTP请求,并利用MongoDb工具类与MongoDB数据库进行交互。
add()
: 添加一个新的文档到user
集合中。list()
: 检索user
集合中的所有文档。listDevices()
: 从另一个数据库penhub
的devices
集合中检索所有文档。
package com.litongjava.tio.web.hello.controller;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.litongjava.tio.http.server.annotation.RequestPath;
import com.litongjava.tio.web.hello.config.MongoDb;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
@RequestPath("/mongodb")
public class MongdbController {
public String add() {
// 获取数据库连接对象
MongoDatabase database = MongoDb.getDatabase();
// 获取集合
MongoCollection<Document> collection = database.getCollection("user");
// 要插入的数据
Document document = new Document("name", "张三").append("sex", "男").append("age", 18);
// 插入如下
collection.insertOne(document);
return "success";
}
public List<Document> list() {
MongoDatabase database = MongoDb.getDatabase();
MongoCollection<Document> collection = database.getCollection("user");
// 查找集合中的所有文档,并遍历
FindIterable<Document> iterable = collection.find();
MongoCursor<Document> cursor = iterable.iterator();
List<Document> lists = new ArrayList<>();
while (cursor.hasNext()) {
Document doucment = cursor.next();
lists.add(doucment);
}
return lists;
}
public List<Document> listDevices(){
MongoDatabase database = MongoDb.getDatabase("penhub");
MongoCollection<Document> collection = database.getCollection("devices");
// 查找集合中的所有文档,并遍历
FindIterable<Document> iterable = collection.find();
MongoCursor<Document> cursor = iterable.iterator();
List<Document> lists = new ArrayList<>();
while (cursor.hasNext()) {
Document doucment = cursor.next();
lists.add(doucment);
}
return lists;
}
}
- 测试访问
- 这部分给出了如何通过HTTP请求调用你的服务的示例。
- 请求
http://localhost/mongodb/add
会在数据库中添加一个新的用户。 - 请求
http://localhost/mongodb/list
会列出所有用户。 - 请求
http://localhost/mongodb/listDevices
会从另一个集合中列出所有设备。
在整个流程中,你的应用程序通过 MongoClientConfiguration
类配置和初始化MongoDB连接,MongoDb
类作为连接的持有者,并在需要时提供连接。控制器 MongdbController
则处理来自客户端的请求,并使用 MongoDb
类与数据库进行交互。
http://localhost/mongodb/list接口返回的数据
[
{
"_id":
{
"counter": 2147426,
"date": "2024-01-21 15:52:04",
"machineIdentifier": 13249596,
"processIdentifier": 14600,
"time": 1705888324000,
"timeSecond": 1705888324,
"timestamp": 1705888324
},
"name": "张三",
"sex": "男",
"age": 18
}
]
事件中心将JSON转换为JSON字符串
您可以使用body_as_json方法来满足您的要求。
示例实施:
jsonbody = event.body_as_json(encoding='UTF-8')
这将直接向我们返回JSON对象
替代方法:
将其获取为字符串,然后将其转换为json对象。
jsonbody = json.loads(event.body_as_str(encoding='UTF-8')))
今天关于如何使用mongo-go-driver有效地将bson转换为json?和mongodb document转json的讲解已经结束,谢谢您的阅读,如果想了解更多关于Mongo 如何将 ISO 日期转换为 BSON 时间戳值、mongodb-go-driver / bson结构转换为bson.Document编码、tio-boot使用mongo-java-driver操作mongodb、事件中心将JSON转换为JSON字符串的相关知识,请在本站搜索。
本文标签: