MongoDB C#- Insert elements into a Nested Array
Today this article will learn MongoDB C#- Insert elements into a Nested Array programmatically using a C# MongoDB driver in .NET or .NET Core application.
We already looked at a simple way of adding or updating a nested array field to the document in general. We shall use the positional operator $[ ] for updating the array field.
We shall use the below sample JSON document and will try to update the below-highlighted value for the given filter criteria.
{
"userId": "12345",
"Name": "Categories",
"Books": [
{
"name": "C# Book",
"catId": "5555"
},
{
"name": "Java Book",
"catId": 12345,
}
]
}
In the above example, we shall try to put or insert the new element in the array as below,
{
"userId": "12345",
"Name": "Categories",
"Books": [
{
"name": "C# Book",
"catId": "5555",
"SubCategories": [
{
"name": "subcat2",
"price": 1000
},
{
"name": "subcat3",
"price": 500
}
]
}
]
}
So in the above example, we will push the array element into an array of Books.
Step I – Establish the connection to the Database using the MongoDB driver,
var _mongoClient = new MongoClient("mongodb://your connection string"); var db = _mongoClient.GetDatabase("Library"); ar collection = db.GetCollection("Books");
Step II – Pushing/Inserting the Nested array element,
var filter = Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("userId", userId),
Builders<BsonDocument>.Filter.Eq("Books.catId", catId));
var update = Builders<BsonDocument>.Update.Push("Books.$.SubCategories", subCat);
await collection.FindOneAndUpdateAsync(filter, update);
In the above code the positional operator $
identifies the array elements that match the filter conditions for Push operation and insert the element at the given.
After the successful execution of the query, we shall see element gets pushed into the array correctly.
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
On a similar line, we can do updates in the array individual element for any deeply nested array element. Please refer to the below article for more details,
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.