FindAndModify () in MongoDb does not return a modified document

I use FindAndModifyto modify a document.

The document has a type User, and the element to change 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()does not return the modified instance, user.webit still has the same meaning as before the update.

When I query Userwith FindOne(), I see the changed value.

Is there anything I need to take care to FindAndModify()return the changed document?

+4
source share
3 answers

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

I am not sure how to send these parameters to the C # driver.

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

, "" .

+2

" ", #:

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

   });
+7

Using FindAndModifyArgs is the right way. All overloads of this method, except for this, are deprecated from version 2.0. Here is an example where we find an object with an IsBusy field in false, and we change it to true, then return it:

FindAndModifyArgs findAndModifyArgs;
FindAndModifyResult mongoResponse;
IMongoQuery   mongoQuery      = Query.EQ  ("IsBusy", false);
UpdateBuilder updateStatement = Update.Set("IsBusy", true);

// Finding a not busy app, and updating it to busy.
findAndModifyArgs = new FindAndModifyArgs()
{
    Query           = mongoQuery,
    Update          = updateStatement,
    SortBy          = null,
    VersionReturned = FindAndModifyDocumentVersion.Modified
 };
mongoResponse = _database.GetCollection<QueuedApp>(collectionName).FindAndModify(findAndModifyArgs);
return BsonSerializer.Deserialize<QueuedApp>(mongoResponse.ModifiedDocument);
+1
source

Source: https://habr.com/ru/post/1537541/


All Articles