如何将字符串值存储在mongodb中作为json对象?

时间:2012-11-22 10:11:49

标签: java json mongodb

我从UI获取数据如下,以下所有输入数据都是字符串。

cust_id:temp001 cust_chart_id:测试 default_chart:false chart_pref_json:{range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20}}

我想在mongodb中存储chart_pref_json。这个chart_pref_json对象实际上存储在db中,作为下面的字符串,

{ "_id" : ObjectId("50aca4caf5d0b0e4d31ef239"), "cust_id" : "temp001", "cust_chart_id" : "testing", "default_chart" : "false", "created_at" : NumberLong("1353491658551"), **"chart_pref_json" : "{range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20}" }**

但实际上我希望将此chart_pref_json存储为json对象,如下所示。

{ "_id" : ObjectId("50aca4caf5d0b0e4d31ef239"), "cust_id" : "temp001", "cust_chart_id" : "testing", "default_chart" : "false", "created_at" : NumberLong("1353491658551"), **"chart_pref_json" : {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20} }**

任何人都可以帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

当您将JSON代码作为字符串时,首先必须解析JSON代码,然后将生成的JSON对象转换为BSON对象。

您可以使用MongoDB附带的类com.mongodb.util.JSONHere is a tutorial

答案 1 :(得分:0)

在将其设置为应用程序中的字段之前,需要使用语言的JSON解码功能将其编码为对象。在PHP中,您可以这样做:

$db->collection->insert( array(
    'cust_id' => 'temp001',
    … your other fields …
    'chart_pref' => json_decode( $varContainingJson )
) );

对于Java,以下示例将有所帮助:

BasicDBObject obj = JSON.parse( varContainingJson ); 

https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/Y3KyG_ZSfJg

中描述的内容

答案 2 :(得分:0)

由于这是一个Java问题,因此以下是使用MongoDB Java驱动程序插入JSON的方法:

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class Main {
    public static void main(String[] args) {
        MongoClientURI uri = new MongoClientURI("mongodb://myuser:mypsw@localhost:27017/mydb");
        MongoClient client = new MongoClient(uri);
        MongoDatabase db = client.getDatabase("mydb");
        String json =
                "{\n" +
                "    \"_id\" : \"MyId\",\n" +
                "    \"foo\" : \"bar\"\n" +
                "}";
        db.getCollection("mycoll").insertOne(Document.parse(json));
    }
}
相关问题