Add item to nested array of nested object using MongoDB C # driver
I am trying to use MongoDB C # Driver to add an item to a nested array inside a BSON document. I've searched SO, but none of the examples I've found match what I'm trying to do.
I have a top-level "Organization" collection in Mongo. It contains several 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, section "Div1" or "Org1" of the organization. What is the optimal way to achieve this? I am trying to use strongly typed versions of MongoDB data access classes where possible.
source to share
There is no typed version query for such a thing, you should use a 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 cannot use the strongly typed version is because of the operator $
.
There is no mongodb C # driver in the current version $
. check here
source to share