Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new object in a nested mongo collection using C# drivers

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

like image 544
Raushan Rauf Avatar asked Apr 18 '26 05:04

Raushan Rauf


1 Answers

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.

  1. An IMongoCollection<T> object called studentsCol
  2. The type of T in that collection is Student
  3. The Id of the student is stored in the variable studentId
  4. The new object to insert is stored in the variable newMark

In 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.

like image 112
Pete Garafano Avatar answered Apr 20 '26 02:04

Pete Garafano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!