How to update collection of supporting documents using MongoDB and C # drivers

I have a collection that contains documents of this form:

{
    "_id" : ObjectId("50f81542a63cfa27fca7df43"),
    "_t" : "ClockRecord",
    "ClockName" : "AAA-TEST123-002",
    "IngestionDateTime" : ISODate("2013-01-17T15:14:10.757Z"),
    "FilesList" : 
    [
        {
            "FileName" : "AAA-TEST123-002.mpg",
            "FileStatus" : "Arriving",
        }, 
        {
            "FileName" : "AAA-TEST123-002.aiff",
            "FileStatus" : "Arriving",
        }
    ]
 }

      

which use these 2 types:

public class ClockRecord : IDatabaseRecord
{
    public ClockRecord()
    {
        FilesList = new List<ClockRecordFile>();
    }

    public string ClockName { get; set; }

    public DateTime IngestionDateTime { get; set; }        

    public List<ClockRecordFile> FilesList { get; set; }

    public BsonObjectId _id { get; set; }
}

public class ClockRecordFile
{
     public string FileName { get; set; }

     public string FileStatus { get; set; }
}

      

I have read many answers on Stack and mongodb sites and this seems to be the correct technique:

var collection = MongoDatabase.GetCollection<ClockRecord>("Clocks");
var update = Update.Set("FilesList.FileStatus", "TEST");
var result = collection.Update(
        Query.And(
                   Query.EQ("_id", clockDocumentID),
                   Query.ElemMatch("FilesList",Query.EQ("FileName","AAA-TEST123-002.mpg"))
                 ),  
                 update, UpdateFlags.Upsert
                              );

      

but nothing happens. How to update FileStatus in subdocu

My ultimate goal is to replace the additional FilesList with another subdocument, so if you know how to do that, that would be a bonus.

+3


source to share


2 answers


It seems there should be $ in the Update.Set section of the code.

It works



var collection = MongoDatabase.GetCollection<ClockRecord>("Clocks");
var update = Update.Set("FilesList.$.FileStatus", "TEST");      <-----$ added here
var result = collection.Update(
        Query.And(
          Query.EQ("_id", clockDocumentID),
          Query.ElemMatch("FilesList",Query.EQ("FileName","AAA-TEST123-002.mpg"))
        ),  
        update, UpdateFlags.Upsert
);

      

+6


source


The problem with the above solution is that it will only update the first comparable document in the array. By using the $ operator, you can only update the first matching document. Currently mongodb does not provide functionality to update multiple array elements using the position operator ($). Check out the link below https://jira.mongodb.org/browse/SERVER-1243



0


source







All Articles