Wednesday 27 November 2013

Use of Java for Inserting data to MongoDB


Example for MongoDB  : Use of Java for Inserting data to MongoDB.

MongoClient mongoClient = null ;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");
BasicDBObject document = new BasicDBObject();
document.put("Id", 12345);
document.put("Name", "abcdhijk");
document.put("Age", 25);
try {
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("1984-05-08T8:30:00.000Z");
document.put("DateOfBirth", date);
} catch (ParseException e) {
e.printStackTrace();
}

String [] interests = {"Reading", "Politics", "Basketball"};
document.put("Interests", interests);

documents.insert(document);



The output on the mongo shell is like :
connect MongoDB using "mongo" command
> show dbs

local 0.078125GB
mongoDB 0.203125GB

> use mongoDB
switched to db mongoDB

> show collections
Documents
system.indexes

> db.Documents.find();
{ "_id" : ObjectId("5296db7e91098e64f3c4faa8"), "Id" : 12345, "Name" : "abcdhijk", "Age" : 25, "DateOfBirth" : ISODate("1984-05-08T03:00:00Z"), "Interests" : [ "Reading", "Politics", "Basketball" ] }

> db.Documents.find().pretty();
{
"_id" : ObjectId("5296db7e91098e64f3c4faa8"),
"Id" : 12345,
"Name" : "abcdhijk",
"Age" : 25,
"DateOfBirth" : ISODate("1984-05-08T03:00:00Z"),
"Interests" : [
"Reading",
"Politics",
"Basketball"
]
}



No comments:

Post a Comment