How do I replace an entire array of subdocuments in MongoDB?
I think you have to do something like this:
var newArray = new BSONArray {
new BSONDocument { { "text", "XYZ" }, { "url", "www.xyz.com" } },
new BSONDocument { { "text", "efg" }, { "url", "www.efg.com" } },
new BSONDocument { { "text", "ijk" }, { "url", "www.ijk.com" } }
};
var update = Update.Set( "links", newArray );
collection.Update( query, update );
Or whatever method you can to cast as a valid BSONValue.
So equivalent to shell:
{ "links" : [ { "text" : "abc" } ] }
> db.collection.update(
{},
{ $set:
{ links: [
{ text: "xyz", url: "something" },
{ text: "zzz", url: "else" }
]}
})
>db.collection.find({},{ _id: 0, links:1 }).pretty()
{ "links" : [
{
"text" : "xyz",
"url" : "something"
},
{
"text" : "zzz",
"url" : "else"
}
]
}
So that works.
You clearly need something else other than embedded code. But hopefully that puts you on the right track.
I am here because I saw 5k views on this post, I'm adding some stuff may be it help other who looking for answer of above
db.collectionName.insertOne({
'links': [
{
"text" : "XYZ",
"url" : "www.xyz.com"
}
]
});
now run this query which help to replace older data
db.collectionName.update(
{
_id: ObjectId("your object Id")
},
{
$set:
{
'links':[ {
"text" : "XYZ1",
"url" : "www.xyz.com1"
} ]
}
});