You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB Java Driver:BsonDocument与Document互转方法咨询

Document与BsonDocument的双向转换(MongoDB Java Driver)

我太懂这种需求了——Document用起来顺手省心,但BsonDocument的类型安全特性在一些严谨场景下确实是刚需。下面就详细说说二者的双向转换方法,都是Java驱动原生支持的,不用额外依赖:

一、Document 转 BsonDocument

你已经实现了这一步,不过还是整理两种常用的原生方法供参考:

  • 方法1:直接调用Document的toBsonDocument()方法(推荐)
    这是最高效的方式,因为Document本身实现了Bson接口,能直接通过驱动的编解码体系转换:

    // 创建一个示例Document
    Document userDoc = new Document("username", "fusionlightcat")
            .append("email", "test@example.com")
            .append("age", 28);
    
    // 获取默认编解码注册表,驱动会自动处理类型映射
    CodecRegistry codecRegistry = MongoClient.getDefaultCodecRegistry();
    // 转换为BsonDocument
    BsonDocument bsonUser = userDoc.toBsonDocument(BsonDocument.class, codecRegistry);
    
  • 方法2:先转JSON再解析(适合需要JSON中间态的场景)
    如果你的业务中需要先把Document转成JSON字符串(比如日志、序列化存储),再转成BsonDocument,可以用这种方式:

    String docJson = userDoc.toJson();
    BsonDocument bsonFromJson = BsonDocument.parse(docJson);
    

二、BsonDocument 转 Document

这是你重点关注的部分,同样有两种实用的原生方法:

  • 方法1:直接用Document的构造器(最简单)
    Document提供了直接接收BsonDocument的构造方法,底层会自动处理BsonValue到Object的类型映射:

    // 创建一个示例BsonDocument
    BsonDocument bsonProduct = new BsonDocument("productId", new BsonObjectId())
            .append("name", new BsonString("MongoDB Guide"))
            .append("price", new BsonDouble(59.9));
    
    // 直接转换为Document
    Document productDoc = new Document(bsonProduct);
    
  • 方法2:通过CodecRegistry解码(适合自定义编解码场景)
    如果你的项目有自定义的编解码规则(比如处理特殊数据类型),可以用驱动的编解码体系来完成转换,更灵活:

    CodecRegistry codecRegistry = MongoClient.getDefaultCodecRegistry();
    // 获取Document的解码器
    Codec<Document> documentCodec = codecRegistry.get(Document.class);
    // 用BsonDocumentReader读取BsonDocument,再解码为Document
    Document docViaCodec = documentCodec.decode(
            new BsonDocumentReader(bsonProduct),
            DecoderContext.builder().build()
    );
    

注意事项

  • 两种类型的转换是双向无损的,驱动会自动处理所有MongoDB支持的类型映射(比如BsonObjectId对应ObjectId,BsonDateTime对应Date等)。
  • 如果你的项目使用了自定义的CodecRegistry(比如注册了自定义类型的编解码器),转换时记得传入你自己的注册表,而不是默认的,避免类型处理不一致。

内容的提问来源于stack exchange,提问作者fusionlightcat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:16:31