Thursday 9 January 2014

How to update multiple value of specific embedded document, inside an array, of a specific document in MongoDB?


How to update multiple value of specific embedded document, inside an array, of a specific document in MongoDB?

MongoDB has a limitation of the same.

for more details please find the below link for your information.

https://jira.mongodb.org/browse/SERVER-1243

for example you have a JSON structure like this ...

{
"_id" : ObjectId("52ce2e4c9109b0e2274a388b"),
"address" : {
"street" : "Aurthor Street 1",
"area" : "Area 1",
"city" : "New York 1",
"country" : "UK"
},
"age" : 29,
"commList" : [
{
"userId" : 1,
"firstName" : "Commenter First Name",
"lastName" : "Commenter Last Name",
"commentText" : "Comment Text",
"date" : ISODate("2014-01-09T05:06:20.283Z")
},
{
"userId" : 1,
"firstName" : "Commenter First Name",
"lastName" : "Commenter Last Name",
"commentText" : "Comment Text 2",
"date" : ISODate("2014-01-09T11:59:57.050Z")
}
],
"commentCount" : 2,
"name" : "Jamse Cook"
}


Now the user name is changed and we need to update the it.

If we try using java code like :

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class, String.class);

DBUpdate.Builder builder = new DBUpdate.Builder();
builder.set("commList.$.firstName", "Puneet");

WriteResult<Person, String> result = coll.update(DBQuery.is("commList.userId", 1), builder);
System.out.println("rows updated :: " + result.getN());

It updates the first occurence only.

you can use the below code and run it on mongoshell which will update the all occurances
var runUpdate = function(){
db.test.find({"commList.userId" : 1}).forEach( function(test) {
for(var i in test.commList){
test.commList[i].firstName = 'abhijit';
}
db.test.save(test);
});
};

db.eval(runUpdate);

Tuesday 7 January 2014

Example of MongoDB with MongoJack

There is need of java mapper to the mongo object and MongoJack is very helpful in the same
to achieve the objective. It uses Jackson as the Java JSON mapper.

You need to add the following jars.

1.  bson4jackson-2.1.0.jar
2.  commons-io-2.4.jar
3.  hamcrest-core-1.3.jar
4.  hamcrest-library-1.3.jar
5.  jackson-annotations-2.1.2.jar
6.  jackson-core-2.1.3.jar
7.  jackson-databind-2.1.3.jar
8.  mongo-java-driver-2.11.3.jar
9.  mongojack-2.0.0-RC5.jar
10. persistence-api-1.0.2.jar


In the example you will find how add, update, updating Embedded field, find and find with some criteria using the MongoJack.


public static void main(String[] args) {
create();
findOne();
updateEmbeddedField();
update();
findOne();
findWithCriteria();
}

public static void create(){

DBCollection dbCollection = getCollection();

JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);
Person person = getPerson();
WriteResult<Person, String> result = coll.insert(person);
Person p = coll.findOne();
Address ad = p.getAddress();
System.out.println("Create o/p ->>  name :: " + p.getName() + " age :: " + p.getAge() + " area :: "+ ad.getArea());
}

public static void updateEmbeddedField(){

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);

DBUpdate.Builder builder = new DBUpdate.Builder();
builder.set("address.area", "Pune");

Person result = coll.findAndModify(DBQuery.is("name", "Jamse Cook"), null, null, false, builder, false, false);
Address ad = result.getAddress();
System.out.println("updateEmbeddedField o/p ->> name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());
}

public static void update(){

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);

DBUpdate.Builder builder = new DBUpdate.Builder();
builder.set("name", "Abhijit");

Person result = coll.findAndModify(DBQuery.is("name", "Jamse Cook"), null, null, false, builder, false, false);
Address ad = result.getAddress();
System.out.println("update o/p  ->>  name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());
}

public static void findOne(){

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);
Person result = coll.findOne();
Address ad = result.getAddress();
System.out.println("find o/p ->> name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());

}

public static void findWithCriteria(){

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);
Person result = coll.findOne(DBQuery.is("name", "Abhijit"));
Address ad = result.getAddress();
System.out.println("findWithCriteria o/p ->>  name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());

}

private static DBCollection getCollection() {
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
DB db = mongoClient.getDB( "jack" );
DBCollection dbCollection = db.getCollection("test");
return dbCollection;
}

private static Person getPerson(){

Person person = new Person();
person.setName("Jamse Cook");
person.setAge(29);

Address address = new Address();
address.setArea("Area 1");
address.setCity("New York 1");
address.setStreet("Aurthor Street 1");
address.setCountry("UK");

person.setAddress(address);

return person;
}

The output on the java console is :


Create o/p ->>  name :: Jamse Cook age :: 29 area :: Area 1
find o/p ->> name :: Jamse Cook age :: 29 area :: Area 1
updateEmbeddedField o/p ->> name :: Jamse Cook age :: 29 area :: Area 1
update o/p  ->>  name :: Jamse Cook age :: 29 area :: Pune
find o/p ->> name :: Abhijit age :: 29 area :: Pune
findWithCriteria o/p ->>  name :: Abhijit age :: 29 area :: Pune

And the output on the mongo shell is :


db.test.find().pretty();
{
"_id" : ObjectId("52cce4e19109c56d473c46eb"),
"address" : {
"area" : "Pune",
"city" : "New York 1",
"country" : "UK",
"street" : "Aurthor Street 1"
},
"age" : 29,
"name" : "Abhijit"
}






Saturday 4 January 2014

Adding JSON to MongoDB Using Java

we can add JSON directly to mongo using Java.

1. In the first example will add josn String directly as shown in the code below.


public static void jsonExmple(){
String jsonString = "{'Name' : 'James Smith', 'Age' : 29," +
 "'Address' : {'area' : 'Area', 'city' : 'New York', 'country' : 'USA'} }";

MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
DB db = mongoClient.getDB( "testJson" );
DBCollection json = db.getCollection("json");
DBObject dbObject = (DBObject)JSON.parse(jsonString);

json.insert(dbObject);

DBCursor jsonDoc = json.find();
while (jsonDoc.hasNext()) {
System.out.println(jsonDoc.next());
}
}

the output on the mongo console would be like :


db.json.find().pretty();
{
"_id" : ObjectId("52c7fead91090c7db49d1604"),
"Name" : "James Smith",
"Age" : 29,
"Address" : {
"area" : "Area",
"city" : "New York",
"country" : "USA"
}
}

2. Another case would be, convert the Java object to json and add the json to mongoDB as shown below.
I have used the google json api to convert Java object to Json.


public static void jsonExample(){

MongoClient mongoClient = null;
try{
mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "testJson" );
DBCollection json = db.getCollection("json");

Person person = new Person();
person.setName("Jamse Cook");
person.setAge(29);

Address address = new Address();
address.setArea("Area");
address.setCity("New York");
address.setStreet("Aurthor Street");
address.setCountry("USA");

person.setAddress(address);

Gson gson = new Gson();
             String jsonString = gson.toJson(person);
             System.out.println(" print the json " + jsonString);
         
             DBObject dbObject = (DBObject)JSON.parse(jsonString);
             json.insert(dbObject);

}catch (Exception e) {

}
}

the output on the mongo console would be like :


{
"_id" : ObjectId("52c7fc479109fd33fdc45793"),
"name" : "Jamse Cook",
"age" : 29,
"address" : {
"street" : "Aurthor Street",
"area" : "Area",
"city" : "New York",
"country" : "USA"
}
}