C#Mongodb FindOneAndReplace或ReplaceOne不起作用

public async Task SomeWork()
        {
            Debug.WriteLine("SomeWork for User : " + Context.User.Identity.Name);
            var userProfile = await UserProfileCollection.Find(u => u._id == Context.User.Identity.Name).FirstOrDefaultAsync();

            userProfile.SuccessfullConnect = true; // currently false
            var up = await UserProfileCollection.FindOneAndReplaceAsync(u => u._id == userProfile._id, userProfile);
            Debug.WriteLine(ObjectDumper.Dump(userProfile));
            Debug.WriteLine(ObjectDumper.Dump(up));
            Debug.WriteLine("Saved SomeWork for User : " + Context.User.Identity.Name);
        }

下面是调试输出.我的文件没有被替换.
检查SuccessfullConnect变量是否仍为false.我检查服务器上也没有更换文件.有时它的工作,有时它不工作.

SomeWork for User : +919933221101
{TestSignalR_Server.Models.UserProfile}
  _id: "+919933221101"
  ...
  SuccessfullConnect: True
  ...

{TestSignalR_Server.Models.UserProfile}
  _id: "+919933221101"
  ...
  SuccessfullConnect: False
  ...

Saved SomeWork for User : +919933221101

最佳答案 方法FindOneAndReplaceAsync应该可以正常工作.

但默认情况下,此方法返回原始文档.

您可以将ReturnDocument更改为ReturnDocument.After以在更改后查看文档.

var options = new FindOneAndReplaceOptions<Profile>
{
     ReturnDocument = ReturnDocument.After
};
var up = await collection.FindOneAndReplaceAsync<Profile>(u => u._id == userProfile._id, userProfile, options);
点赞