繁体   English   中英

使用Spring Boot在MongoDB中对JSON对象进行插入和获取操作

[英]Insert and Get operations on JSON object in MongoDB with Spring Boot

如何在MongoDB中保存具有不同层次结构的JSON对象?

例如:-JSON

{“名称”:“ abc”,“密码”:“ xyz”,“地址”:{“街道”:“ ghgjk”,“ pin”:25646},“ readingHabbits”:[“ jkjsdj”,“ sdkhks”, “ jlcsd”],“ eatingHabbits”:{“ internalObjOne”:{“ dkks”:“ jdskdfl”,“ lfld”:“ hfslvlsk”},“ internalObjectSecond”:{“ cjdlksl”:“ hcdkjnjkcs”,“ cjsdjljsl”:“ chsdskjc“}}}

如何使用SpringBoot和Java将上述JSON值存储到不同集合中的MongoDB中?

另外,当我执行repository.findAll()时,如何获得相同的结果?

它看起来应该像这样:

db.getCollection("images").insertOne(
        new Document("name", "abc")
        .append("password", "xyz")
        .append("address",
                new Document()
                .append("street", "ghgjk")
                .append("pin", 25646))
        .append("readingHabbits", Arrays.asList("jkjsdj", "sdkhks", "jlcsd"))
        .append("eatingHabbits", Arrays.asList(
                new Document()
                .append("internalObjOne",
                        new Document()
                        .append("dkks", "jdskdfl")
                        .append("lfld", "hfslvlsk")),
                new Document()
                .append("internalObjectSecond",
                new Document()
                        .append("cjdlksl", "hcdkjnjkcs")
                        .append("cjsdjljsl", "chsdskjc"))
        )
)
);
thanks for the answer, But I think I didn't made myself clear.
Suppose I have a json object.
{ "name": "abc", "password": "xyz", "address": { "street": "ghgjk", "pin": 25646 }, "readingHabbits": [ "jkjsdj", "sdkhks", "jlcsd" ], "eatingHabbits": { "internalObjOne": { "dkks": "jdskdfl", "lfld": "hfslvlsk" }, "internalObjectSecond": { "cjdlksl": "hcdkjnjkcs", "cjsdjljsl": "chsdskjc" } } }

Base class :-

@Document(collection="user")
public class User{
@Id
private String id;
private String name;
private String password;
@DBRef
private Address address;
@DBRef
private ReadingHabbits readingHabbits;
//setter and getter 
}

@Document(collection="address")
public class Address{
@Id
private String id;
private String street;
private int pin;
//setter and getter 
}

Do we need to create separate classes for "ReadingHabbits" and "EatingHabbits" ?

If not then is the above approach correct to map two different entities with DBRef and save it to two different collection in MongoDB?

Or do we have any other way to do the same operation ?


----------

暂无
暂无

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

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