【问题标题】:Is it possible to populate additional fields with a json object for Mongo java?是否可以使用 Mongo java 的 json 对象填充其他字段?
【发布时间】:2012-06-20 03:49:50
【问题描述】:

我知道有一个 BasicDBObject 可以让你去做:

BasicDBObject info = new BasicDBObject();

info.put("x", 203);
info.put("y", 102);

我遇到的问题是该值只能是原始类型。 我有一个 json 对象,我想与无法修改的公共数据一起存储,但想在单个 mongo 文档中描述 json 对象。我可以做些什么来做类似的事情:

BasicDBObject info = new BasicDBObject();
info.put("Name", "John");
info.put("Main Hobby", "Hiking");
info.put("Albums", json-string-with-nested-arrays);

总而言之,我正在寻找一种方法,允许我在同一文档中存储除了键值对之外的 json 对象(假设我拥有的“json-string-with-nested-arrays”是不可修改,因此我无法在其中插入其他属性。)我该如何完成?

下面是 json-string-with-nested-arrays:

{"data":[{"stuff":[
    {"onetype":[
        {"id":1,"name":"John Doe"},
        {"id":2,"name":"Don Joeh"}
    ]},
    {"othertype":[
        {"id":2,"company":"ACME"}
    ]}]
},{"otherstuff":[
    {"thing":
        [[1,42],[2,2]]
    }]
}]}

【问题讨论】:

    标签: java mongodb mongo-java


    【解决方案1】:

    如果 "json-string-with-nested-arrays" 是 JSON 字符串,那么您可以在 mongo-java-driver 中执行类似的操作。

    info.put("Albums", JSON.parse(json-string-with-nested-arrays));
    

    JSON.parse() 方法是 mongo-java-driver 的一部分

    【讨论】:

    • json-string-with-nested-arrays 必须是完美格式化的 Json String
    • 无法正常运行,因为它只将 JSON 对象存储为字符串而不是 JSON 对象。
    • 我不这么认为。 JSON.parse() 方法将 JSON 字符串转换为 mongo 兼容的 JSON。我不明白为什么会发生这种情况。我可以很好地使用它
    • 如果您使用 jsonp 或 json 进行 ajax 调用,您会注意到键“Albums”的值是一个字符串(json 对象的)。
    • 你能告诉我你的json-string-with-nested-arrays吗?当您进行 Ajax 调用时,Accept 请求标头是什么
    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多