Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating an embedded document in MongoDB with official C# driver
    primarykey
    data
    text
    <p>If I have a Company collection which contains embedded Divisions:</p> <pre><code>{ "_id": 1 "_t": "Company", "Name": "Test Company" "Divisions": [ { "_id": 1 "_t": "Division", "Name": "Test Division 1" }, { "_id": 2 "_t": "Division", "Name": "Test Division 2" } ] } </code></pre> <p>What is the best way to save/update an entire Division when using the <a href="http://www.mongodb.org/display/DOCS/CSharp+Language+Center" rel="noreferrer">official 10gen C# driver</a>? (The latest 0.9 release.)</p> <p>I'm using Update.AddToSetWrapped to add Divisions, and that works fine, but I'd also like to be able to update documents depending on their _id.</p> <p>For example, if I define the following Update method: </p> <pre><code>public void UpdateDivision(IDivision division) { var mongo = MongoServer.Create(_connectionString); var database = mongo.GetDatabase(_databaseName); var query = Query.EQ("_id", division.CompanyId); var update = Update.AddToSetWrapped("Divisions", division); database.GetCollection&lt;Company&gt;("Company") .Update(query, update, UpdateFlags.Upsert, SafeMode.True); } </code></pre> <p>and call it like so: </p> <pre><code>var division = GetDivisionById(1); division.Name = "New Name"; UpdateDivision(division); </code></pre> <p>Then a new instance of Division will be added to the set, because although the "_id" is still 1, the Name is different, and therefore it is a unique document.</p> <p>So what is there a good way to update a whole embedded document?</p> <p>Until I come up with a better solution I am going to first <code>$pull</code> the original Division and then <code>$addToSet</code> with the modified Division. That works but is obviously not ideal as it performs two separate updates.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload