No SQL > Mongo DB > How to insert a Document in Mongo Database2
How to insert a Document in Mongo Database2
MongoDB is a scalable, high-performance, open source NoSQL database.
It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation,
MapReduce and Server-side JavaScript execution.
This requires the library mongo-2.8.0.jar to be present in the classpath.
The following example shows how to insert a document in Mongo database.
try {
//Connect to mongoDB with given IP and PORT
Mongo mongo = new Mongo("localhost", 27017);
//Get the database object
DB database = mongo.getDB("mytestdb");
//Gets a collection with a given name.
//If the collection does not exist, a new collection is created.
DBCollection collection = database.getCollection("mynums");
//collection.drop();
//Create and insert document to collection
DBObject document = null; int num = 0;
for (int i = 0 ; i < 20 ; i ++) {
num = i + 1;
document = new BasicDBObject();
//Assign your own id for this document
document.put("_id", num);
document.put("num", num);
document.put("even", (num % 2 == 0));
document.put("num^2", Math.pow(num, 2));
//Saves a document to the database
collection.insert(document);
}
//Queries for all objects in this collection
DBCursor dbCursor = collection.find();
DBObject record = null;
while (dbCursor.hasNext()) {
record = dbCursor.next();
System.out.println(record);
}