I want to add a new object in the nested Mongo collection using C# drivers, please find below sample json.
I have collection called students similar to below.
{
"_id" : ObjectId("5a866be6f843b648a0bac9ab"),
"FIstName" : "Bob",
"LastName" : "mark",
"MarkList" : [
{
"SUbject" : "science",
"Mark" : "80",
"Rank" : "10",
}
],
}
Now I wanted to insert a new subject object under the Marklist Array using C# drivers,
{
"SUbject" : "Physics",
"Mark" : "80",
"Rank" : "10",
}
Also I have created Classes for above properties.
Kindly suggest some ideas.
Thanks in advance
The easiest thing to do would be to use the $push operator but $addToSet would work as well depending on your requirements.
If we construct this in the Mongo Shell, you'll get something like
db.students.update({"_id": ObjectId("5a866be6f843b648a0bac9ab")},
{
$push: {
"MarkList": {
"Subject": "Physics",
"Mark": 80,
"Rank": 10
}
}
})
So translating that into C#, lets assume you have a few things already.
IMongoCollection<T> object called studentsColT in that collection is StudentstudentIdnewMarkIn this case, the following code will accomplish what you're looking for.
studentsCol.UpdateOneAsync(
Builders<Student>.Filter.Eq(x => x.Id, studentId),
Builders<Student>.Update.Push(x => x.MarkList, newMark));
If you want to use $addToSet you just change Update.Push to Update.AddToSet.
Note: If you opt for $addToSet please be sure to read how MongoDB determines if a document already exists in the array.
If the value is a document, MongoDB determines that the document is a duplicate if an existing document in the array matches the to-be-added document exactly; i.e. the existing document has the exact same fields and values and the fields are in the same order. As such, field order matters and you cannot specify that MongoDB compare only a subset of the fields in the document to determine whether the document is a duplicate of an existing array element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With