2016-11-22 112 views
-2
{ 
    "colorsArray" : [ { 
     "colorName" : "red", 
     "hexValue" : "#f00" 
    }, { 
     "colorName" : "green", 
     "hexValue" : "#0f0" 
    }, { 
     "colorName" : "blue", 
     "hexValue" : "#00f" 
    }, { 
     "colorName" : "cyan", 
     "hexValue" : "#0ff" 
    }, { 
     "colorName" : "magenta", 
     "hexValue" : "#f0f" 
    }, { 
     "colorName" : "yellow", 
     "hexValue" : "#ff0" 
    }, { 
     "colorName" : "black", 
     "hexValue" : "#000" 
    } ] 
} 

回答

1

你在找什麼是「如何將文檔插入到mongodb中」。像這樣的東西應該工作。

db.colors.insertMany(
    [ { 
     "colorName" : "red", 
     "hexValue" : "#f00" 
    }, { 
     "colorName" : "green", 
     "hexValue" : "#0f0" 
    }, { 
     "colorName" : "blue", 
     "hexValue" : "#00f" 
    }, { 
     "colorName" : "cyan", 
     "hexValue" : "#0ff" 
    }, { 
     "colorName" : "magenta", 
     "hexValue" : "#f0f" 
    }, { 
     "colorName" : "yellow", 
     "hexValue" : "#ff0" 
    }, { 
     "colorName" : "black", 
     "hexValue" : "#000" 
    } ] 
) 

現在你需要找出你想如何做到這一點。在java中有多種方式來實現這一點。

如果您是新手使用基於文檔的數據庫,並希望保持容易,我會考慮使用Spring data。但是你可以只使用MongoDB的java驅動程序。有很多關於如何做的教程,如this

0
mongoimport --host localhost --port 37017 --username user --password pass --collection collectionName --db databaseName --file fileName 
+0

感謝山姆!但我想直接從java中完成。 – donny

0

下面是我的代碼示例,您可以根據需要使用它。

DBObject obj = (DBObject) com.mongodb.util.JSON.parse(sample_json); 
put all obj into a list, 

List<DBObject> listObject = new ArrayList<>(); 
list.add(obj); 
//save them into database: 
new MongoClient().getDB("dbname").getCollection("collection").insert(list); 

UPDATE ANSEWR:

總代碼:

package com.demo.mongo; 

import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.DBCursor; 
import com.mongodb.DBObject; 
import com.mongodb.Mongo; 
import com.mongodb.util.JSON; 

/** 
* Java MongoDB : Convert JSON data to DBObject and insert it to dab 
* 
*/ 

public class JsonApp { 
    public static void main(String[] args) { 

     try { 

      Mongo mongo = new Mongo("ipaddress", 27017); 
      DB db = mongo.getDB("dbname"); 
      DBCollection collection = db.getCollection("dummyColl"); 

      // convert JSON to DBObject directly 

      DBObject obj = (DBObject) JSON.parse("sample_json"); 

      collection.insert(dbObject); 

      System.out.println("Done"); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

請給我提供整個代碼,因爲m得到錯誤:列表 listObject = new ArrayList <>(); – donny

+0

可能是一個參考...! – donny