如何使用 Java Mongo DB 驱动程序版本 3 将 BasicDBObject 转换为 Mongo 文档? [英] How to convert a BasicDBObject to a Mongo Document with the Java Mongo DB driver version 3?

查看:181
本文介绍了如何使用 Java Mongo DB 驱动程序版本 3 将 BasicDBObject 转换为 Mongo 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java Mongo DB 驱动程序版本 3 中,API 与版本 2 相比发生了变化.因此这样的代码不再编译:

BasicDBObject personObj = new BasicDBObject();collection.insert(personObj)

集合插入仅适用于 Mongo 文档.

处理旧代码我需要问的问题:

将 BasicDBObject 转换为文档的最佳方法是什么?

解决方案

We Can Convert BasicDBObject通过以下方式Document

public static Document getDocument(DBObject doc){if(doc == null) 返回 null;返回新文档(doc.toMap());}

as Document 本身是 Map 的实现.

BasicDBObject 也可以在 DBObject 中捕获,因为 BasicDBObjectDBObject 的实现.>

@Black_Rider 也适合您

In the Java Mongo DB driver version 3 the API has changed as compared to the version 2. So a code like this does not compile anymore:

BasicDBObject personObj = new BasicDBObject();
collection.insert(personObj) 

A Collection insert works only with a Mongo Document.

Dealing with the old code I need to ask the question:

What is the best way to convert a BasicDBObject to a Document?

解决方案

We Can Convert BasicDBObject to Document by the following way

public static Document getDocument(DBObject doc)
{
   if(doc == null) return null;
   return new Document(doc.toMap());
}

as Document itself is an implementation of Map<String,Object>.

and BasicDBObject can be too be catch in DBObject as BasicDBObject is an implementation of DBObject.

@Black_Rider for you too

这篇关于如何使用 Java Mongo DB 驱动程序版本 3 将 BasicDBObject 转换为 Mongo 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆