如何使用java将数据从Json文件导入Mongodb
我正在努力将数据从如何使用java将数据从Json文件导入Mongodb,java,json,mongodb,shell,command-line,Java,Json,Mongodb,Shell,Command Line,我正在努力将数据从Json文件导入Mongodb。 我可以在命令行中使用mongoimport命令 我探索并尝试了很多,但无法使用java从Json文件导入 sample.json { "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" : {"company name" : "company1", "designation" : "SSE" } } { "test_id" : 254
Json
文件导入Mongodb
。我可以在命令行中使用
mongoimport命令
我探索并尝试了很多,但无法使用java从Json文件导入
sample.json
{ "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" :
{"company name" : "company1", "designation" : "SSE" }
}
{ "test_id" : 254152, "name" : "Alex", "age" : "26", "Job" :
{"company name" : "company2", "designation" : "ML" }
}
谢谢你抽出时间。
~Ganesh~假设您可以分别读取JSON字符串。例如,您读取第一个JSON文本
{ "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" :
{"company name" : "company1", "designation" : "SSE" }
}
并将其分配给一个变量(字符串json1),下一步是解析它
DBObject dbo = (DBObject) com.mongodb.util.JSON.parse(json1);
将所有dbo放入列表
List<DBObject> list = new ArrayList<>();
list.add(dbo);
编辑:
在最新的MongoDB版本中,您必须使用文档而不是DBObject,并且添加对象的方法现在看起来有所不同。下面是一个更新的示例:
进口产品包括:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
代码如下所示(参考编辑上方的文本):
你也可以用列表的方式来做。但是你需要
new MongoClient().getDataBase("db").getCollection("collection").insertMany(list);
但我认为这个解决方案存在一个问题。键入时:
db.collection.find()
在mongo shell中获取集合中的所有对象,结果如下所示:
{ "_id" : ObjectId("56a0d2ddbc7c512984be5d97"),
"test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" :
{ "company name" : "company1", "designation" : "SSE"
}
}
这与以前不完全相同。我自己也有类似的“问题”,最终使用了with和Morphia
虽然这听起来有点像用大锤敲碎螺母,但它实际上非常易于使用、健壮、性能相当好,并且易于维护代码
小提示:如果要重用它,需要将测试id
字段映射到MongoDB的\u id
步骤1:创建带注释的bean
您需要提示Jackson如何将数据从JSON文件映射到POJO。为了便于阅读,我将课程缩短了一点:
@JsonRootName(value="person")
@Entity
public class Person {
@JsonProperty(value="test_id")
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
至于嵌入式文档作业
,请查看链接的POJO数据绑定示例
步骤2:映射POJO并创建数据存储
在应用程序初始化过程中,需要映射带注释的POJO。既然您已经应该有一个MongoClient,我将重用它;)
进行实际导入
现在导入给定的JSON文件变得非常简单
public Boolean importJson(Datastore ds, ObjectMapper mapper, String filename) {
try {
JsonParser parser = new JsonFactory().createParser(new FileReader(filename));
Iterator<Person> it = mapper.readValues(parser, Person.class);
while(it.hasNext()) {
ds.save(it.next());
}
return Boolean.TRUE;
} catch (JsonParseException e) {
/* Json was invalid, deal with it here */
} catch (JsonMappingException e) {
/* Jackson was not able to map
* the JSON values to the bean properties,
* possibly because of
* insufficient mapping information.
*/
} catch (IOException e) {
/* Most likely, the file was not readable
* Should be rather thrown, but was
* cought for the sake of showing what can happen
*/
}
return Boolean.FALSE;
}
public Boolean importJson(数据存储ds、对象映射器映射器、字符串文件名){
试试{
JsonParser parser=new JsonFactory().createParser(新文件读取器(文件名));
迭代器it=mapper.readValues(解析器,Person.class);
while(it.hasNext()){
保存(it.next());
}
返回Boolean.TRUE;
}捕获(JSONParsee异常){
/*Json无效,请在此处处理*/
}捕获(JsonMappingException e){
/*杰克逊无法绘制地图
*bean属性的JSON值,
*可能是因为
*映射信息不足。
*/
}捕获(IOE异常){
/*最有可能的是,该文件不可读
*应该被扔掉,但是被扔掉了
*咳嗽是为了展示可能发生的事情
*/
}
返回Boolean.FALSE;
}
通过一点重构,可以在Jackson注释bean的通用导入器中进行转换。
显然,我遗漏了一些特殊情况,但这超出了本回答的范围。对于3.2驱动程序,如果您有一个mongo集合和一个json文档集合,例如:
MongoCollection<Document> collection = ...
List<String> jsons = ...
或散装:
collection.insertMany(
jsons.stream().map(Document::parse).collect(Collectors.toList())
);
Runtime r=Runtime.getRuntime()强>
进程p=null强>
//dir是指向mongoimport所在位置的路径
File dir=新文件(“C:/Program Files/MongoDB/Server/3.2/bin”)强>
//这一行将在giving dir中打开shell,导入命令与在命令promote中使用mongoimport完全相同
p=r.exec(“c:/windows/system32/cmd.exe/c mongoimport--db mydb--collection student--type csv--file student.csv--headerline”,null,dir)我今天刚刚面对这个问题,并用另一种不同的方式解决了它,而这里没有一种方式能让我满意,所以请享受我的额外贡献。性能足以导出30k文档并将它们导入到我的Springboot应用程序中进行集成测试用例(需要几秒钟)
首先,导出数据的方式至关重要。
我想要一个文件,其中每行包含一个文档,我可以在java应用程序中解析
mongo db --eval 'db.data.find({}).limit(30000).forEach(function(f){print(tojson(f, "", true))})' --quiet > dataset.json
然后我从我的resources文件夹中获取文件,解析它,提取行,并使用mongoTemplate处理它们。可能需要一个缓冲区
@Autowired
private MongoTemplate mongoTemplate;
public void createDataSet(){
mongoTemplate.dropCollection("data");
try {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(DATASET_JSON);
List<Document> documents = new ArrayList<>();
String line;
InputStreamReader isr = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
documents.add(Document.parse(line));
}
mongoTemplate.insert(documents,"data");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Autowired
私有MongoTemplate MongoTemplate;
public void createDataSet(){
mongoTemplate.dropCollection(“数据”);
试一试{
InputStream InputStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(DATASET_JSON);
列表文档=新建ArrayList();
弦线;
InputStreamReader isr=新的InputStreamReader(inputStream,Charset.forName(“UTF-8”));
BufferedReader br=新的BufferedReader(isr);
而((line=br.readLine())!=null){
documents.add(Document.parse(行));
}
mongoTemplate.插入(文件,“数据”);
}捕获(例外e){
抛出新的运行时异常(e);
}
}
List jsonList=new ArrayList();
net.sf.json.JSONArray数组=net.sf.json.JSONArray.fromObject(json);
用于(对象:数组){
net.sf.json.JSONObject jsonStr=(net.sf.json.JSONObject)JSONSerializer.toJSON(object);
Document jsnObject=Document.parse(jsonStr.toString());
添加(jsnObject);
}
collection.insertMany(jsonList);
公共静态无效导入SV(字符串路径){
试一试{
列表=新的ArrayList();
MongoDatabase db=DbConnection.getDbConnection();
db.createCollection(“新集合”);
MongoCollection collection=db.getCollection(“newCollection”);
BufferedReader reader=新的BufferedReader(新文件读取器(路径));
弦线;
而((line=reader.readLine())!=null){
字符串[]项=l
jsons.stream().map(Document::parse).forEach(collection::insertOne);
collection.insertMany(
jsons.stream().map(Document::parse).collect(Collectors.toList())
);
mongo db --eval 'db.data.find({}).limit(30000).forEach(function(f){print(tojson(f, "", true))})' --quiet > dataset.json
@Autowired
private MongoTemplate mongoTemplate;
public void createDataSet(){
mongoTemplate.dropCollection("data");
try {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(DATASET_JSON);
List<Document> documents = new ArrayList<>();
String line;
InputStreamReader isr = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
documents.add(Document.parse(line));
}
mongoTemplate.insert(documents,"data");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
List<Document> jsonList = new ArrayList<Document>();
net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(json);
for (Object object : array) {
net.sf.json.JSONObject jsonStr = (net.sf.json.JSONObject)JSONSerializer.toJSON(object);
Document jsnObject = Document.parse(jsonStr.toString());
jsonList.add(jsnObject);
}
collection.insertMany(jsonList);
public static void importCSV(String path) {
try {
List<Document> list = new ArrayList<>();
MongoDatabase db = DbConnection.getDbConnection();
db.createCollection("newCollection");
MongoCollection<Document> collection = db.getCollection("newCollection");
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
while ((line = reader.readLine()) != null) {
String[] item = line.split(","); // csv file is "" separated
String id = item[0]; // get the value in the csv assign keywords
String first_name = item[1];
String last_name = item[2];
String address = item[3];
String gender = item[4];
String dob = item[5];
Document document = new Document(); // create a document
document.put("id", id); // data into the database
document.put("first_name", first_name);
document.put("last_name", last_name);
document.put("address", address);
document.put("gender", gender);
document.put("dob", dob);
list.add(document);
}
collection.insertMany(list);
}catch (Exception e){
System.out.println(e);
}
}