How can I change multiple fields in multiple docs in one in MongoDB C#

Viewed 52

I want to add a social feature to my app. Each user can send an invitation to other users and once the other user approves the invitation they are "friends". The operation of approving an invitation includes several actions:

  1. add each userId inside the other user friends list
  2. remove the invitation from the user who sent the invitation
  3. remove the approval invitation from the user receiving the invitation

I want to do all these actions as one atomic operation.

Currently, I'm doing it like this:

public class FriendsData
{
    public long _id;//UserId
    public long[] FriendsId;
    public long[] SentInvitations;
    public long[] AwaitingForApprovalInvitations;
}

public void ApproveInvitation(FriendsData userData, FriendsData friendData)
{
       m_friends.FindOneAndUpdate(string.Format("{{_id: {0}}} ", userData._id), Builders<FriendsData>.Update.AddToSet("FriendsId", friendData._id)
                                                                                                  .Pull("ActiveSentInvitations", friendData._id));

       m_friends.FindOneAndUpdate(string.Format("{{_id: {0}}} ", friendData._id), Builders<FriendsData>.Update.AddToSet("FriendsId", userData._id)
                                                                                       .Pull("AwaitingForApprovalInvitations", userData._id));
}

Is there a better way to do this? I'm worried that the DB will change between the two update actions.

0 Answers
Related