MongoDB using AddtoSet to Add an element to the array if not exists
Today in this article, We will perform the update to MongoDB and Add An Element To The Array If Not Exists- the AddtoSet example. We will see how to insert/Push an element to an array programmatically based on the condition if that element doesn’t exist.
Today in this article, we will cover below aspects,
We shall see the C# MongoDB driver in .NET or .NET Core example to perform the same.
We already looked at a simple way of adding or updating a nested array field to the document in general where we had used “push” and positional operator $[ ] for updating the array field.
Today we will see another array operator “AddtoSet” operator for performing the same.
Using AddtoSet operator helps us perform below out of the box,
MongoDB Push Vs AddtoSet
– Adds a value to an array unless the value is already present
– If a value already exists, AddtoSet does nothing to that array.
– Ensures that there are no duplicate items added to the array
– It does not affect existing duplicate elements
Let’s 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",
"SubCategories": [
{
"name": "subcat2",
"price": 1000
},
{
"name": "subcat3",
"price": 500
}
]
}
]
}
In the above example, we shall try to add new elements in the array only if that element doesn’t exist in the array.
Step I – Establish the connection to the Database using MongoDB C# driver
Below is a basic skeleton code to establish the connection to the Database using the MongoDB C# driver.
var _mongoClient = new MongoClient("mongodb://your connection string"); var db = _mongoClient.GetDatabase("Library"); ar collection = db.GetCollection("Books");
Step II – Using AddtoSet to push/insert the element in the array
Using AddtoSet to push/insert the element in the array,
var filter = Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("userId", userId),
Builders<BsonDocument>.Filter.Eq("Books.catId", catId));
var update = Builders<BsonDocument>.Update.AddToSet("Books.$.SubCategories", subCat);
await collection.FindOneAndUpdateAsync(filter, update);
In the above example, the positional operator $
identifies the array elements that match the filter conditions for AddtoSet to perform the insert of the element if that element doesn’t exist in the array already.
After successful execution of the query, we shall see the element gets pushed in the array correctly.
If the element form is a simple primitive type like (int or string) or a complex type (as shown in the above example) we see AddtoSet deliver the same behavior and make query preparation and execution simple.
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
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.