Note that there are some explanatory texts on larger screens.

plurals
  1. POHowto MongoDB update / $set entire subdocument
    primarykey
    data
    text
    <p>In my MongoDB, I have Document1, as seen below. I want to reach into the "main.accounts" (and later, "main.entries") document, and update ($set) an entire sub-document in a "content' array. Wrt sub-documents, so far, I've been able to add and remove a document to and from a "content" sub-array. But in this case, I want to update the entire document; Not just update ($set) one property in a matched document. </p> <p>Below, I've tried using just a $set, a $set with $elemMatch. And I've also tried findAndModify, but to no avail. Of course, I've i) RTFM, looked all around ii) the internet and iii) SO, to find a solution. Has anyone been able to update an entire document in this manner? </p> <p>Thanks Tim </p> <p><strong>Update try 1</strong> - this is the only update that works, but sets the entire "content" array to the hash … { "fu" : "bar" }</p> <pre> db.bookkeeping.update( { owner : "twashing@gmail.com", "content.content.tag" : "account", "content.content.id" : "one" }, { $set : { "content.$.content" : { "fu" : "bar" } } } ) </pre> <p><strong>Update try 2</strong> - this doesn't fail, but doesn't update the document in question</p> <pre> db.bookkeeping.update( { owner : "fu", thing : { $elemMatch : { "content.content.tag" : "account", "content.content.id" : "one" } } }, { $set : { "thing" : { "fu" : "bar" } } } ) </pre> <p><strong>Update try 3</strong> - this doesn't fail, but doesn't update the document in question</p> <pre> db.bookkeeping.update( { thing : { $elemMatch : { owner : "fu" , "content.content.tag" : "account", "content.content.id" : "one" } } }, { $set : { "thing.content.content.$" : { "fu" : "bar" } } } ) </pre> <p><strong>Document1</strong></p> <pre> { "_id" : "fid", "content" : [ { "content" : [ { "id" : "one", "tag" : "account" }, { "id" : "two", "tag" : "account" }, { "id" : "three", "tag" : "account" }, { "id" : "four", "tag" : "account" }, { "id" : "five", "tag" : "account" } ], "id" : "main.accounts", "tag" : "accounts" }, { "tag" : "journals", "id" : "main.journals", "content" : [ { "tag" : "journal", "id" : "generalledger", "name" : "generalledger", "type" : "", "balance" : "", "content" : [ { "tag" : "entries", "id" : "main.entries", "content" : [ ] } ] } ] } ], "owner" : "fu", "tag" : "fubar" } </pre>
    singulars
    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.
 

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