Syntax error Insert array where element does not exist else update it (with multiple conditions)?

Insert array where element does not exist else update it (with multiple conditions)?



You can use bulkWrite(). Let us create a collection with documents −

> db.demo105.insertOne( { _id:'101', Name:'Chris', Details:[{ Marks1:60, Marks2:70, Marks3:70 }, { Marks1:70, Marks2:70, Marks3:90 }] } );
{ "acknowledged" : true, "insertedId" : "101" }

Display all documents from a collection with the help of find() method −

> db.demo105.find().pretty();

This will produce the following output −

{
   "_id" : "101",
   "Name" : "Chris",
   "Details" : [
      {
         "Marks1" : 60,
         "Marks2" : 70,
         "Marks3" : 70
      },
      {
         "Marks1" : 70,
         "Marks2" : 70,
         "Marks3" : 90
      }
   ]
}

Following is the query to insert array where element does not exist else update it with multiple conditions −

> 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
   }
}

Display all documents from a collection with the help of find() method −

> db.demo105.find().pretty();

This will produce the following output −

{
   "_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
      }
   ]
}
Updated on: 2020-03-30T11:40:23+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements