How to import data into Mongodb from Json file using java

I am trying to import data into Mongodbfrom a file Json.
I can do the same on the command line using mongoimport command.
I studied and tried a lot, but could not import from a Json file using java.

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" } 
    }

Thank you for your time. ~ ~ Ganesha

+4
source share
6 answers

Suppose you can read the JSON string accordingly. For example, you read the first JSON text

{ "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" : 
   {"company name" : "company1", "designation" : "SSE" } 
}

and assign it to a variable (String json1), the next step is to parse it,

DBObject dbo = (DBObject) com.mongodb.util.JSON.parse(json1);

put all dbo in the list,

List<DBObject> list = new ArrayList<>();
list.add(dbo);

:

new MongoClient().getDB("test").getCollection("collection").insert(list);

EDIT:

MongoDB Documents DBObject, -. :

:

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

( EDIT):

Document doc = Document.parse(json1);
new MongoClient().getDataBase("db").getCollection("collection").insertOne(doc);

.

new MongoClient().getDataBase("db").getCollection("collection").insertMany(list);

, . :

db.collection.find()

mongo, , :

{ "_id" : ObjectId("56a0d2ddbc7c512984be5d97"),
    "test_id" : 1245362, "name" : "ganesh", "age" : "28", "Job" :
        { "company name" : "company1", "designation" : "SSE" 
    }
}

, .

+7

Runtime r = Runtime.getRuntime();

p = null;

- dir - , mongoimport.

dir = ( "C:\Program Files\MongoDB\Server\3.2\bin" );

- dir, , mongoimport promotion

p = r.exec( "c:\windows\system32\cmd.exe/c mongoimport --db mydb --collection student --type csv --file student.csv - headerline", null, );

+2

"" Jackson POJO Morphia.

, , , .

: test_id MongoDB _id, .

1. bean

, 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;
  }

}

Job, POJO.

2: POJO

- POJO. MongoClient, ;)

Morphia morphia = new Morphia();
morphia.map(Person.class);

/* You can reuse this datastore */
Datastore datastore = morphia.createDatastore(mongoClient, "myDatabase");

/* 
 * Jackson ObjectMapper, which is reusable, too,
 * does all the magic.
 */
ObjectMapper mapper = new ObjectMapper();

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

, Jackson, beans. , , .

+1

3.2, mongo json-, :

MongoCollection<Document> collection = ...
List<String> jsons = ...

:

jsons.stream().map(Document::parse).forEach(collection::insertOne);

:

collection.insertMany(
        jsons.stream().map(Document::parse).collect(Collectors.toList())
); 
+1

-, , . , 30 . Springboot ( ).

-, , . , 1 , java.

mongo db --eval 'db.data.find({}).limit(30000).forEach(function(f){print(tojson(f, "", true))})' --quiet > dataset.json

Then I get the file from the resource folder, parse it, extract the lines and process them using mongoTemplate. May use a buffer.

@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);
    }
}
0
source
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);
0
source

All Articles