4

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.

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

collection.Update This is no longer available in current driver
@Kalanamith Use Builders<TDocument>.Update.AddToSet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.