Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Insert array where element does not exist else update it (with multiple conditions)?
To insert array elements when they don't exist or update them when they do using multiple conditions, use bulkWrite() with multiple updateOne operations. This allows conditional updates and insertions in a single atomic operation.
Syntax
db.collection.bulkWrite([
{
"updateOne": {
"filter": { "field": "value", "array": { "$elemMatch": { conditions } } },
"update": { "$set": { "array.$.field": "newValue" } }
}
},
{
"updateOne": {
"filter": { "field": "value", "array": { "$not": { "$elemMatch": { conditions } } } },
"update": { "$push": { "array": { newElement } } }
}
}
]);
Sample Data
db.demo105.insertOne({
_id: '101',
Name: 'Chris',
Details: [
{ Marks1: 60, Marks2: 70, Marks3: 70 },
{ Marks1: 70, Marks2: 70, Marks3: 90 }
]
});
{ "acknowledged" : true, "insertedId" : "101" }
Example: Conditional Update and Insert
Update existing elements matching specific conditions, or insert new elements if conditions aren't met ?
db.demo105.bulkWrite([
{
"updateOne": {
"filter": {
"_id": "101",
"Details": {
"$elemMatch": { Marks2: 70, Marks3: 70 }
}
},
"update": {
"$set": { "Details.$.Marks3": 96 }
}
}
},
{
"updateOne": {
"filter": {
"_id": "101",
"Details": {
"$not": {
"$elemMatch": { Marks2: 70, Marks3: 70 }
}
}
},
"update": {
"$push": { "Details": { Marks1: 94, Marks2: 97, Marks3: 99 } }
}
}
},
{
"updateOne": {
"filter": { "_id": 101 },
"update": {
"$setOnInsert": {
"Details": [
{ Marks1: 34, Marks2: 67, Marks3: 87 }
]
}
},
"upsert": true
}
}
]);
{
"acknowledged" : true,
"deletedCount" : 0,
"insertedCount" : 0,
"matchedCount" : 2,
"upsertedCount" : 1,
"insertedIds" : { },
"upsertedIds" : {
"2" : 101
}
}
Verify Result
db.demo105.find().pretty();
{
"_id" : "101",
"Name" : "Chris",
"Details" : [
{
"Marks1" : 60,
"Marks2" : 70,
"Marks3" : 96
},
{
"Marks1" : 70,
"Marks2" : 70,
"Marks3" : 90
},
{
"Marks1" : 94,
"Marks2" : 97,
"Marks3" : 99
}
]
}
{
"_id" : 101,
"Details" : [
{
"Marks1" : 34,
"Marks2" : 67,
"Marks3" : 87
}
]
}
How It Works
- First operation: Updates existing elements where Marks2=70 and Marks3=70
- Second operation: Inserts new elements when the condition doesn't match
- Third operation: Creates new document with default values using upsert
Conclusion
Use bulkWrite() with multiple updateOne operations to conditionally update or insert array elements. Combine $elemMatch for positive conditions and $not for negative conditions to achieve complex conditional logic.
Advertisements
