简体   繁体   English

MongoDB-合并两个DBObject

[英]MongoDB - Merging two DBObjects

I am writing a model factory, for which I use JSON to load up a MongoDB DBObject like this: 我正在编写一个模型工厂,为此我使用JSON来加载MongoDB DBObject,如下所示:

import com.mongodb.util.JSON;
DBObject dbObject = (DBObject) JSON.parse("{'name':'jack', 'age':30}");

Now, I am trying to break up my JSON files such that I can load up a DBObject with one JSON file, and if needed I can augment the DBObject with another JSON file. 现在,我正在尝试分解JSON文件,以便可以使用一个JSON文件加载DBObject,并且如果需要,可以使用另一个JSON文件扩展DBObject。

Although it sounds weird, imagine having a set of different type of users. 尽管听起来很奇怪,但请想象一下有一组不同类型的用户。 Like, BasicUser, AdvancedUser etc. I can have a JSON file to load up BasicUser, and put the other non-overlapping details of an AdvancedUser in another JSON file. 像BasicUser,AdvancedUser等。我可以有一个JSON文件来加载BasicUser,并将AdvancedUser的其他非重叠详细信息放在另一个JSON文件中。 I can make AdvancedUser extend BasicUser, and so I can just combine the contents of the two JSON files to create an AdvancedUser model. 我可以使AdvancedUser扩展BasicUser,因此可以将两个JSON文件的内容结合起来以创建AdvancedUser模型。

How could I achieve something like this? 我怎样才能实现这样的目标?

I believe putAll is what you want. 我相信putAll是您想要的。

DBObject obj1 = (DBObject) JSON.parse("{'name':'jack', 'age':30}");
DBObject obj2 = (DBObject) JSON.parse("{'role':'admin'}");
obj1.putAll(obj2);
System.out.println(obj1.toString()); //{ "name" : "jack" , "age" : 30 , "role" : "admin"}

我决定通过递归地遍历一个DBObject并将内容传输到另一个数据库来实现自己的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM