简体   繁体   中英

Add sub document to mongodb with java

It's the first time that I used mongodb and I added document from java in this way:

//document populated with for cycle
document.append(element.getID().toString(), new Document("EL_ID", feedback.getPos(i).getID())
                    .append("name", element.getName())
                    .append("vote", 5)
                );

//and write (replaceOne is correct for my program's logic)
BasicDBObject searchQuery = new BasicDBObject().append("_id", MainDocID);
collection.replaceOne(searchQuery, document);

the result is:

{
"_embedded": {},
"_links": { ... },
"_type": "DOCUMENT",
"_id": { ... },

"element_ID_1": {
    "EL_ID": {
        "$oid": "element_ID_1"
    },
    "name": "one",
    "vote": 5
},
"element_ID_2": {
    "EL_ID": {
        "$oid": "element_ID_2"
    },
    "name": "two",
    "vote": 5
},
"_created_on": "date"
}

I think it's correct to put these elements in "_embedded" and it's also more ordered, but I don't know how do this.

I want achieve this result:

{
    "_embedded": {

        "element_ID_1": {
          "EL_ID": {
            "$oid": "element_ID_1"
          },
          "name": "one",
          "vote": 5
        },

        "element_ID_2": {
          "EL_ID": {
            "$oid": "element_ID_2"
          },
          "name": "two",
          "vote": 5
        }
    },
      "_links": {},
      "_type": "DOCUMENT",
      "_id": {},
      "_created_on": "date"
}

or for example (same principle): _embedded -> elements_lista -> "element_ID_n"

I couldn't find an example applicable to my case (from java code), any suggestion is appreciate, thanks.

This needs to be handled in the way you are inserting the data into the Map.

Previously, you were setting the keys EL_ID, name and vote into the main Map. However you need to create a map say _embedded and keys mentioned above needs to be set into it.

When this overall DTO is inserted into the DB, it will be saved in a structure you have mentioned.

经过一些尝试,我已经解决了简单地创建一个包含所有元素的ArrayList并将其附加到文档中的字符串键“_embedded”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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