Wednesday 27 November 2013

Embedded/sub document example of MongoDB with JAVA.


Creating a complex JSON for in MongoDB.
Embedded/sub document example of MongoDB with JAVA.
Lets aim to add a JSON as shown below in mongoDB.
{
"Id" : 12345,
"Name" : "opqrst",
"Age" : 25,
"DateOfBirth" :  ("1984-05-08"),
"Interests" : [ "Reading", "Politics", "Basketball" ],

"Address" : {
"addressDetail" : "flat no 103, A Wing, Ram Nagar",
"area" : "Rahatani",
"city" : "Pune",
"pincode" : 411027,
"state" : "MAHARASHTRA",
"country" : "INDIA"
}
}


public static void create(){
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", "opqrst");
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);

BasicDBObject address = new BasicDBObject();
address.put("addressDetail", "flat no 103, A Wing, Ram Nagar" );
address.put("area", "Rahatani");
address.put("city", "Pune");
address.put("pincode", 411027);
address.put("state", "MAHARASHTRA");
address.put("country", "INDIA");

document.put("Address", address);

documents.insert(document);

}

The output on the mongo shell is like :

> db.Documents.find().pretty();
{
"_id" : ObjectId("5296e4fe91093f95cc8b84e7"),
"Id" : 12345,
"Name" : "opqrst",
"Age" : 25,
"DateOfBirth" : ISODate("1984-05-08T03:00:00Z"),
"Interests" : [ "Reading", "Politics", "Basketball" ],
"Address" : {
"addressDetail" : "flat no 103, A Wing, Ram Nagar",
"area" : "Rahatani",
"city" : "Pune",
"pincode" : 411027,
"state" : "MAHARASHTRA",
"country" : "INDIA"
}
}


Creating more complex Structure using MongoDB and JAVA

Example of creating array of embedded/sub document.
The JSON structure is :

{
"Id" : 12345,
"Name" : "abcdefxyz",
"Age" : 25,
"DateOfBirth" : ("1984-05-08"),
"Interests" : [ "Reading", "Politics", "Basketball"],

"address" : {
"addressDetail" : "flat no 333, Q Wing, Sita Nagar",
"area" : "Aundh",
"city" : "Pune",
"pincode" : 411017,
"state" : "MAHARASHTRA",
"country" : "INDIA"
},

"BooksRead" : [
{
"name" : "The Immortals of Meluha",
"authorName" : "Amish Tripathi",
"publishedBy" : "Westland Press"
},
{
"name" : "The Krishna Key",
"authorName" : "Ashwin Sanghi",
"publishedBy" : "Westland Ltd"
},
{
"name" : "Sita: An Illustrated Retelling of Ramayana",
"authorName" : "Devdutt Pattanaik",
"publishedBy" : "Mehata Publishing Ltd"
}
]
}


public static void create(){
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", "abcdefxyz");
document.put("Age", 25);
document.put("DateOfBirth", new Date());

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

BasicDBObject address = new BasicDBObject();
address.put("addressDetail", "flat no 333, Q Wing, Sita Nagar" );
address.put("area", "Aundh");
address.put("city", "Pune");
address.put("pincode", 411017);
address.put("state", "MAHARASHTRA");
address.put("country", "INDIA");

document.put("address", address);

List<BasicDBObject> booksRead = new ArrayList<BasicDBObject>();
BasicDBObject book1 = new BasicDBObject();
book1.put("name", "The Immortals of Meluha");
book1.put("authorName", "Amish Tripathi");
book1.put("publishedBy", "Westland Press");
booksRead.add(book1);

BasicDBObject book2 = new BasicDBObject();
book2.put("name", "The Krishna Key");
book2.put("authorName", "Ashwin Sanghi");
book2.put("publishedBy", "Westland Ltd");
booksRead.add(book2);

BasicDBObject book3 = new BasicDBObject();
book3.put("name", "Sita: An Illustrated Retelling of Ramayana");
book3.put("authorName", "Devdutt Pattanaik");
book3.put("publishedBy", "Mehata Publishing Ltd");
booksRead.add(book3);

document.put("BooksRead", booksRead);
documents.insert(document);

}

The output on the mongo shell is like :

> db.Documents.find().pretty();

{
"_id" : ObjectId("5296e987910919e6768c9391"),
"Id" : 12345,
"Name" : "abcdefxyz",
"Age" : 25,
"DateOfBirth" : ISODate("1984-05-08T03:00:00Z"),
"Interests" : [ "Reading", "Politics","Basketball"],
"address" : {
"addressDetail" : "flat no 333, Q Wing, Sita Nagar",
"area" : "Aundh",
"city" : "Pune",
"pincode" : 411017,
"state" : "MAHARASHTRA",
"country" : "INDIA"
},
"BooksRead" : [
{
"name" : "The Immortals of Meluha",
"authorName" : "Amish Tripathi",
"publishedBy" : "Westland Press"
},
{
"name" : "The Krishna Key",
"authorName" : "Ashwin Sanghi",
"publishedBy" : "Westland Ltd"
},
{
"name" : "Sita: An Illustrated Retelling of Ramayana",
"authorName" : "Devdutt Pattanaik",
"publishedBy" : "Mehata Publishing Ltd"
}
]
}

31 comments:

  1. Great post..I was searching for a similar kind of code .
    thank you

    ReplyDelete
  2. Excellent. This is what I have been trying to do..All I have to do is replace Rahatani by Wakad :-)

    ReplyDelete
  3. Thanks for the post. Helped me a lot.

    ReplyDelete
    Replies
    1. Now only I learning mongoDB, Today i tried complex structure program. But 1 hour waste. I got your site in google, now i relief(easy to understand), Thanks brother. update program's based on mongodb. Really thanks bro.:-)

      Delete
    2. Welcome sakthi...Will keep updating more on MongoDB...Or may be you tell me the problems and I would try to solve those for you...
      I would be happy to solve the problem you are facing...

      Delete
  4. Thank you dude,i had doubt normalization data modeling using java, can you help me, send some related links .

    ReplyDelete
    Replies
    1. Hi Sanjeev,

      Please find the below links related to normalization ....

      http://www.mongodb.com/presentations/webinar/mongodb-schema-design-principles-and-practice

      http://blog.mongodb.org/post/72874267152/transitioning-from-relational-databases-to-mongodb

      Delete
  5. i got it, but i want to update these fields.

    ReplyDelete
    Replies
    1. check if this is of any help to you http://abhijitbashetti.blogspot.in/2014/01/how-to-update-multiple-value-of.html

      Delete
    2. BasicDBObject objectToBeUpdated = new BasicDBObject();
      objectToBeUpdated.put("$push", new BasicDBObject("address.area","NewArea"));

      This is With considering the above my JSON where in Address is the embedded document

      Delete
  6. "BooksRead" : [
    {
    "id":1,
    "name" : "The Immortals of Meluha",
    "authorName" : "Amish Tripathi",
    "publishedBy" : "Westland Press"
    },
    {
    "id":2,
    "name" : "The Krishna Key",
    "authorName" : "Ashwin Sanghi",
    "publishedBy" : "Westland Ltd"
    },
    {
    "id":3,
    "name" : "Sita: An Illustrated Retelling of Ramayana",
    "authorName" : "Devdutt Pattanaik",
    "publishedBy" : "Mehata Publishing Ltd"
    }


    my json data is like above...
    i want update fields with id basis.

    ReplyDelete
    Replies
    1. This would resolve your problem
      http://abhijitbashetti.blogspot.in/2014/01/example-of-mongodb-with-mongojack.html

      Delete
  7. and can we get count of embedding document.

    ReplyDelete
    Replies
    1. I am not very sure of this ...
      But I think If you are using any framework e.g MongoJack
      then you will get the collection of the embedded documents where in you can get the count of Embedded documents....

      Delete
  8. Replies
    1. http://abhijitbashetti.blogspot.in/2014/01/example-of-mongodb-with-mongojack.html.

      Delete
  9. Strong and useful

    ReplyDelete
  10. how to retrieve image from mongodb? help me

    ReplyDelete
  11. how to fetch name of the books read in monogdb as a list

    ReplyDelete
  12. can there be a chance to update an embedded document whhih is in another embedded document?

    ReplyDelete
  13. Can anyone help me to fetch mongo subdocument based on date range using Java Springb oot

    ReplyDelete