Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindAndModify() in MongoDb does not return changed document

Tags:

c#

mongodb

I am using FindAndModify to modify a document.

The document is of type User and the element to modify is called web:

var users = _db.GetCollection<User>(UserCollectionName);

var userQuery = Query.EQ("user", "testuser");

var findAndModifyResult = users.FindAndModify(
       new FindAndModifyArgs()
       {
           Query = userQuery,
           Update = Update.Set("web", "testweb")   
       });

// user.web is unchanged in the result
var user = findAndModifyResult.GetModifiedDocumentAs<User>();

// user.web is changed in the result
user = users.FindOne(userQuery);

GetModifiedDocumentAs() doesn't return the changed instance, user.web still has the same value it had before the update.

When I query the user with FindOne() I see the changed value.

Is there something I need to take care of, so that FindAndModify() returns the modified document?

like image 784
thumbmunkeys Avatar asked Dec 20 '22 15:12

thumbmunkeys


2 Answers

To expand on Will Shavers' answer, this is the correct method with the c# driver:

collection.FindAndModify(
   new FindAndModifyArgs()
   {
       Query = query,
       Update = updateOperation,
       // this needs to be set
       VersionReturned = FindAndModifyDocumentVersion.Modified

   });
like image 85
thumbmunkeys Avatar answered Mar 29 '23 06:03

thumbmunkeys


You need to query with : {safe: true, 'new' : true}

I'm not sure how to send these options in the c# driver.

http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#findandmodify-method

Looks like the final argument is the "new" option.

like image 34
Will Shaver Avatar answered Mar 29 '23 04:03

Will Shaver