Reputation: 39
i m using put method as basicobj.put("1",obj.setAddre()+obj1.setFName()); while updating i want to update only the address but here the enitre value is updating.Value for key "1" is updating. is there any method or give me hint to update only the address. Here is my code...
public class AccessObjectID{
public static void main(String[] args)throws UnknownHostException {
AccessObject obj1 = new AccessObject();
obj1.setAddre("Sector No:-42,Los Angeles,USA");
obj1.setFirstName("Jack");
obj1.setLName("Reacher");
obj1.setEmail("[email protected]");
obj1.setPNumber("02024568963");
AccessObject obj2 = new AccessObject();
obj2.setAddre(",USA");
obj2.setFirstName("udsy ");
obj2.setLName("jhkjhkjad");
obj2.setEmail("[email protected]");
obj2.setPNumber("02024568963");
MongoClient mongoclient = new MongoClient("localhost",27017);
DB dbobj = mongoclient.getDB("demo");
DBCollection colc = dbobj.getCollection("demo_1");
BasicDBObject basicdbobj = new BasicDBObject();
colc.remove(basicdbobj);
basicdbobj.put("1", obj1.getAddress()
+obj1.getFName()
+obj1.getLName()
+obj1.getEmail()
+obj1.getPNumber());
basicdbobj.put("2", obj2.getAddress()
+obj2.getFName()
+obj2.getLName()
+obj2.getEmail()
+obj2.getPNumber());
colc.insert(basicdbobj);
DBCursor db = colc.find();
while(db.hasNext()){
System.out.println(db.next());
}
System.out.println("********************************** \n"+"UPDATE");
obj1.setAddre("Pune,India");
BasicDBObject update = new BasicDBObject();
update.put("1",obj1.getAddress());
BasicDBObject updateobj = new BasicDBObject();
updateobj.put("$set",update);//new BasicDBObject().append("",""));//update);
colc.update(basicdbobj, updateobj);
db = colc.find();
while(db.hasNext()){
System.out.println(db.next());
}
colc.save(basicdbobj);
}
}
Upvotes: 0
Views: 133
Reputation: 11308
As far as I understood, you are looking to replace the address value of a document which has the address value "Pune,India". If that's the case try the following:
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("$set", new BasicDBObject().append("1", "New Address"));
BasicDBObject searchQuery = new BasicDBObject().append("1", "Pune,India");
colc.update(searchQuery, newDocument);
Upvotes: 1