Reputation: 8406
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 a lot of Stack replies 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 do I update a FileStatus in the sub-document?
My final goal is to replace a FilesList sub document with a different sub-document so if you know how to do that as well that would be a bonus.
Upvotes: 3
Views: 5927
Reputation: 19037
The Problem with above solution is that it will update only first matching document in the array .Using $ operator you can only update first matching document .Currently mongodb does not provide functionality to update multiple array elements using position operator($) .Have a look at the below link https://jira.mongodb.org/browse/SERVER-1243
Upvotes: 0
Reputation: 8406
Seems there should be a $ in the Update.Set portion of the code.
This 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
);
Upvotes: 7