Search code examples
c#mongodbmongodb-querymongodb-.net-drivermongodb-update

MongoDB - How to update a single object in the array of objects inside a document


I have the following document structure:

{
  "Agencies": [
    {
      "name": "tcs",
      "id": "1",
      "AgencyUser": [
        {
          "UserName": "ABC",
          "Code": "ABC40",
          "Link": "http.ios.com",
          "TotalDownloads": 0
        },
        {
          "UserName": "xyz",
          "Code": "xyz20",
          "Link": "http.ios.com",
          "TotalDownloads": 0
        }
      ]
    }
  ]
}

Like I have multiple agencies and each agency contains a list of agents.

What I am trying is to pass the Code and update the TotalDownloads field of the agent that matches the code.

For example, if someone uses the code ABC40 so I need to update the field TotalDownloads of the agent called "ABC".

What I have tried is as below:

public virtual async Task UpdateAgentUsersDownloadByCode(string Code)
{
    var col = _db.GetCollection<Agencies>(Agencies.DocumentName);
    FilterDefinition<Agencies> filter = Builders<Agencies>.Filter.Eq("AgencyUsers.Code", Code);
    UpdateDefinition<Agencies> update = Builders<Agencies>.Update.Inc(x => x.AgencyUsers.FirstOrDefault().TotalDownloads, 1);
    await col.UpdateOneAsync(filter, update);
}

It is giving me the following error:

Unable to determine the serialization information for x => x.AgencyUsers.FirstOrDefault().TotalDownloads.

Where I'm wrong?


Solution

  • Note: From the attached sample document, the array property name: AgencyUser is not matched with the property name that you specified in the update operation, AgencyUsers.


    Use arrayFilters with $[<identifier>] positional filtered operator to update the element(s) in the array.

    MongoDB syntax

    db.Agencies.update({
      "AgencyUsers.Code": "ABC40"
    },
    {
      $inc: {
        "AgencyUsers.$[agencyUser].TotalDownloads": 1
      }
    },
    {
      arrayFilters: [
        {
          "agencyUser.Code": "ABC40"
        }
      ]
    })
    

    Demo @ Mongo Playground

    MongoDB .NET Driver syntax

    UpdateDefinition<Agencies> update = Builders<Agencies>.Update
        .Inc("AgencyUsers.$[agencyUser].TotalDownloads", 1);
    
    UpdateOptions updateOptions = new UpdateOptions
    {
        ArrayFilters = new[]
        {
            new BsonDocumentArrayFilterDefinition<Agencies>(
                new BsonDocument("agencyUser.Code", Code)
                )
        }
    };
    UpdateResult result = await col.UpdateOneAsync(filter, update, updateOptions);
    

    Demo

    enter image description here