如何从Java导入JSON文件到mongodb

时间:2016-11-22 06:41:47

标签: java json mongodb parsing import

class MyClass{
private:
  std::vector<Texture *> _textures;
public:
  void addATexture(int textureWidth,int textureHeight){
      Texture * tex = new Texture(textureWidth,textureHeight);
      _textures.push_back(tex);`enter code here`
  } 
}

3 个答案:

答案 0 :(得分:2)

以下是我的代码示例。您可以根据需要使用它。

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);

更新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();
        } 
    }
}

答案 1 :(得分:0)

您正在寻找的是“如何将文档插入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

答案 2 :(得分:0)

=Regex(Source, replace)