I have an existing MongoDB document that contains the field files
(as well as other fields). The files
field is an object and now I want to update this field with several nested documents. I have been successful in inserting one nested document with the following syntax:
db.collection.updateOne(
{ "id": 1 },
{
$set: {
"files":
{
"filename1": {
"a": "Lorem ipsum dolor",
"b": "Sit amet consectetur",
"c": "Adipiscing elit"
}
}
}
})
Next, I tried inserting 2 more documents at the same time into the file
field which failed
db.collection.updateOne(
{ "id": 1 },
{
$set: {
"files":
{
"filename2": {
"d": "Lorem ipsum dolor",
"e": "Sit amet consectetur",
"f": "Adipiscing elit"
}
}
{
"filename3": {
"g": "Duis aute irure",
"h": "Labore et dolore",
"i": "Eiusmod tempor incididunt"
}
}
}})
After this didn't work, I attempted to insert the records one by one using the first code block, but inserting filename2
(I did not want to overwrite existing filename1
). This document was inserted into the files
object but overwrote the existing document filename1
. I tried several different variations but nothing has worked.
Any feedback/assistance regarding how to nest several documents within a field would be helpful.