Update the embedded document from the collection using the version of MongoDB and C # new driver (2.0)

I have a model with an inline service list:

public class Project
{
    public ObjectId Id { get; set; }
    public List<Service> Services { get; set; }
}

and

public class Service
{
    public int Id { get; set; }
    public MachineInfo Info { get; set; }
}

I want to change the Info property corresponding to the request for projectId and serviceId into a list item. With the old driver, this was:

var result = collection.Update(
        Query.And(
          Query.EQ("_id", projectId),
          Query.ElemMatch("Services", Query.EQ("Id", serviceId))
        ), 
var update = Update.Set("Services.$.Info", newInfo);
Collection.Update(query, update);

But using the new driver, I cannot use the position operator '$':

var filter = Builders<Project>.Filter.And(Builders<Project>.Filter.Eq(x => x.Id, projectId),
    Builders<Project>.Filter.ElemMatch(x => x.Services, x => x.Id == serviceId));
var update = Builders<Project>.Update.Set(x => x.$.Info, newInfo);
this.collection.UpdateOneAsync(filter, update);

Any idea how to do this? Use an outdated driver?

+4
source share
1 answer

You can do 2 things here ... Either use the line as you did in 1.x ...

Builders<Project>.Update.Set("Services.$.Info", newInfo);

or use ElementAt (-1)

Builders<Project>.Update.Set(x => x.Services.ElementAt(-1).Info, newInfo);
+6
source

All Articles