Reputation: 7897
I am trying to use the MongoDB C# Driver to add an item to a nested array inside of a BSON document. I have searched SO, but none of the examples I have found so far match what I am trying to do.
I have a top-level "Organizations" collection in Mongo. This contains multiple Organization objects with the following structure:
{
"id":"Org1",
"Name":"First Org",
"Divisions":[
{
"id":"Div1",
"Name":"First Division",
"UsersInDivision":[
"User1",
"User2"
]
}
]
}
I have the following POCO classes
public class Organization
{
public string Id { get; set; }
public string Name { get; set; }
public IList<Division> Divisions { get; set; }
}
public class Division
{
public string Id { get; set; }
public string Name { get; set; }
public IList<string> UsersInDivision { get; set; }
}
I would like to add the string "User3" to the UsersInDivision collection, of Division "Div1" or Organization "Org1". What is the optimal way to achieve this? I am trying to use the strongly typed versions of MongoDB data access classes where possible.
Upvotes: 4
Views: 4410
Reputation: 6371
There is no typed version query for do such a thing, you have to use string based query
var query = Query.And(Query.EQ("id", "Org1"), Query.EQ("Divisions.id", "Div1"));
collection.Update(query, Update.AddToSet("Divisions.$.UsersInDivision", "User3"));
The reason you cant use strongly typed version is $
operator.
There is no $
in current version of mongodb c# driver. check here
Upvotes: 5