简体   繁体   English

创建具有Java文档列表的mongo文档

[英]Create mongo document that has a list of documents in Java

I would like to create a mongo document in Java to insert into my mongo collection. 我想用Java创建一个mongo文档,以插入到我的mongo集合中。 Currently, the mongo document I am using has no list of documents in it and I want to add one to it. 当前,我正在使用的mongo文档中没有文档列表,我想向其中添加一个。

My document should look something like this: 我的文档应如下所示:

{
 id : 1,
 events : [
           { event_id : 1, processed : false},
           { event_id : 2, processed : false},
           .
           .
          ],
 assigned_user : 32
}

To create the mongo document, I am forced to create a 要创建mongo文档,我不得不创建一个

Map<String, Object> dataFields

then transform it to a mongo document. 然后将其转换为mongo文档。

So to add the list of Documents I need, I thought of creating 因此,要添加我需要的文档列表,我想创建

 List<Document> events

then creating a document for each event I need, then add it to the list of events . 然后为我需要的每个事件创建一个文档,然后将其添加到events列表中。

Finally I would simply add the list events to the map dataFields , then create the final mongo document. 最后,我只需将列表events添加到地图dataFields ,然后创建最终的mongo文档。

Would this work? 这行得通吗? If not, what is the flaw? 如果没有,那么缺陷是什么? Logic or implementation? 逻辑还是实现?

If you have an idea, try it. 如果您有想法,请尝试一下。 And if your project environment does not allow you to try, sandbox it. 如果您的项目环境不允许您尝试,请将其沙箱化。 I'll give it a go, but my Java is rusty, and I dont have the JDK on this computer. 我会尝试一下,但是我的Java生锈了,这台计算机上没有JDK。 Start with this : 从此开始:

public class MongoSandbox {

    public static void main(String[] args) throws UnknownHostException {

        // Connect to local test db
        MongoClientURI uri  = new MongoClientURI("mongodb://localhost:27017/test"); 
        MongoClient client = new MongoClient(uri);
        MongoDatabase db = client.getDatabase(uri.getDatabase());

        // Get a test collection
        MongoCollection<Document> docs = db.getCollection("docs");

        /* Create a dummy list of events  */
        List<Document> events = new ArrayList<Document>();
        events.add(new Document("random", "data"));
        events.add(new Document("random", "data2"));
        events.add(new Document("random", "data3"));

        // Create your main document
        Document mainDoc = new Document("events", events);
        docs.insert(mainDoc);

        client.close();
    }
}

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

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