【问题标题】:How to store a string value in mongo db as an json object?如何将字符串值存储在 mongodb 中作为 json 对象?
【发布时间】:2012-11-22 10:11:49
【问题描述】:

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

cust_id : temp001 cust_chart_id : 测试 默认图表:假 chart_pref_json : {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20} }

我正在尝试将 chart_pref_json 存储在 mongodb 中。这个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} }**

谁能帮我解决这个问题。

【问题讨论】:

  • 当我试图在 mongodb 中保存 "chart_pref_json" : {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20} } 时,它被保存为字符串 " {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20}" 而我想存储为 json {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding: 20} 没有“”。
  • 想要的和不需要的结果看起来相同。

标签: java json mongodb


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    由于这是一个 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));
        }
    }
    

    【讨论】:

      【解决方案3】:

      在将其设置为应用程序中的字段之前,您需要使用您的语言的 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进行了描述

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        • 1970-01-01
        • 2013-07-04
        • 2011-08-09
        • 1970-01-01
        • 2015-09-14
        • 2017-11-13
        相关资源
        最近更新 更多