MongoDB update Nested Array element/object using C#

C NET MongoDB Update Nested Array elementobject

Today in this article, we shall see and learn how to perform an update to specific elements in a nested array using the C# MongoDB driver.

You would find multiple needs to update arrays element at a specific location and for the given filter match criteria.

We already looked at multiple ways of adding or updating a new field to the document.

Today in this article, we will cover below aspects,

Please visit below article to understand that scenarios,

This could be a legitimate use case for you on updating the collection array for specific elements.

Example:

{
"_id":"5fd807a4c8b5b535c8b9a6c4"},

"userid":123456,

"books":[
         {"book_name":"book_name1","price":88}, 
         {"book_name":"book_name2","price":50}, 
         {"book_name":"book_name3","price":30}
         ]
}

We shall try to update “price” element from the nested array,

Getting started – MongoDB Update Nested Array element/object using C#

Please create any .NET/.NET Core application.

Please add the MongoDB driver NuGet package using the Nuget Package manager.

PM> Install-Package MongoDB.Driver -Version 2.9.3

I shall keep the MongoDB driver interface use here simple enough to concentrate on how to add new fields to the existing documents.

Please visit for better approaches like using Dependency Injection (DI) or IOC here,

Hence we shall be specifying the filter criteria as matching ‘UserId’ and ‘book_name’.

Likewise, you can use suitable filter criteria for your need.

Then for each match, we are updating the required data i.e the ‘price’ tag for the record.

Please see below generic implementation using BsonDocument.

Please see similar below type safe implementation using Library and Books class.

            
            var filterBuilder = Builders<Library>.Filter;
            var filter = filterBuilder.Eq(x => x.userid, inputUserId) &
                filterBuilder.ElemMatch(doc => doc.books, el => el.book_name == inputBookName);

            var updateBuilder = Builders<Library>.Update;
            var update = updateBuilder.Set(doc => doc.books[-1].price, inputPriceBook);

            collection.UpdateOne(filter, update);

Below are the Library and Book model entities created based on the mongo schema.

 public class Library
    {
        public int userid { get; set; }
        public Book[] books { get; set; }
    }

    public class Book
    {
        public string book_name { get; set; }
        public int price { get; set; }
    }

The above logic once executed will perform the update for the highlighted price array element based on the filter criteria(as matching ‘UserId’ and ‘book_name’.)

Performing Insert/Delete in array

If you need to Delete or Insert in array element , please see below article for more details,

Do you have any comments or suggestions? Can we make the above code better?

Please sound off your comments below.

References :



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *