Question

I am using ObjCMongoDB as a cocoa wrapper for accessing mongoDB. I am facing difficulty in a scenario where I have to find and replace a document with a new document. Can any one help me by pointing out the code/API of ObjCMongoDB to use.

For example:

{
"_id" : { "$oid" : "51de4ed737965b2d233f4862"} ,
"milestone" : "Application 7.1 release" ,
"pendingtasklist" : [ task1 , task2 , task3]
}

here I have to replace pendingtasklist with new list and result should be

{
"_id" : { "$oid" : "51de4ed737965b2d233f4862"} ,
"milestone" : "Application 7.1 release" ,
"someotherlist" : [ task12 , task33 , task32]
}

I have attached the code I am using to achieve this, but without success

NSError *connectionError = nil;
MongoConnection *dbConn = [MongoConnection connectionForServer:@"127.0.0.1:27017" error:&connectionError];


MongoDBCollection *collection = [dbConn collectionWithName:@"mydb.milestones"];

MongoKeyedPredicate *predicate = [MongoKeyedPredicate predicate];
[predicate keyPath:@"milestone" matches:@"Application 7.1 release"];

MongoUpdateRequest *updateReq = [MongoUpdateRequest updateRequestWithPredicate:predicate  firstMatchOnly:YES];
NSDictionary *milestoneDict = @{@"problemlist": @[@"12345",@"112244",@"55543",@"009009"],@"milestone":@"Application 7.1 release"};
[updateReq replaceDocumentWithDictionary:milestoneDict];

BOOL result = [collection updateWithRequest:updateReq error:&connectionError];

Before my collection will have documents like this:

{ "_id" : { "$oid" : "51de4ed737965b2d233f4862"} , "milestone" : "Application 7.1 Release" , "problemlist" : [ 12345 , 112244 , 55543]}
{ "_id" : { "$oid" : "51de4ed737965b2d233f4864"} , "milestone" : "Application 7.1 UAT" ,  "problemlist" : [ 33545 , 7654 , 8767]}
Was it helpful?

Solution

If the value were staying the same, you would just rename the key:

  • -[MongoUpdateRequest keyPath:renameToKey:]

But since the values are changing, you should just unset the old key and set the new one.

  • -[MongoUpdateRequest unsetValueForKeyPath:]
  • -[MongoUpdateRequest keyPath:setValue:]

As I mentioned above you can do this with a single update request.

OTHER TIPS

In order to rename a field, you need to remove the old one, and add the new one. In this case, you would have to run two separate queries for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top