- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is it possible to utilize $addToSet multiple times in the same update?
Yes, it is possible using the UPDATE() method. Let us create a collection with documents −
> db.demo27.insertOne({"StudentDetails":{"101":{"Subject":["Java"]}}}); { "acknowledged" : true, "insertedId" : ObjectId("5e15f9e822d07d3b95082e7f") } > db.demo27.insertOne({"StudentDetails":{"101":{"Subject":["MySQL"]}}}); { "acknowledged" : true, "insertedId" : ObjectId("5e15f9eb22d07d3b95082e80") }
Display all documents from a collection with the help of find() method −
> db.demo27.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e15f9e822d07d3b95082e7f"), "StudentDetails" : { "101" : { "Subject" : [ "Java" ] } } } { "_id" : ObjectId("5e15f9eb22d07d3b95082e80"), "StudentDetails" : { "101" : { "Subject" : [ "MySQL" ] } } }
Following is the query to implement $addToSet multiple times in the same update −
> db.demo27.update({}, {$addToSet: {"StudentDetails.101.Subject": "MongoDB"}}, {upsert: true}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo27.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e15f9e822d07d3b95082e7f"), "StudentDetails" : { "101" : { "Subject" : [ "Java", "MongoDB" ] } } } { "_id" : ObjectId("5e15f9eb22d07d3b95082e80"), "StudentDetails" : { "101" : { "Subject" : [ "MySQL" ] } } }
- Related Articles
- Is it possible to make an insert or an update in the same MySQL query?
- Is it possible to use UPDATE query with LIMIT in MySQL?
- Is it possible to catch multiple Java exceptions in single catch block?
- Is it possible to have View and table with the same name in MySQL?
- How is it possible for a MySQL trigger to execute multiple statements?
- Is it possible to override a Java method of one class in same?
- Pull and add to set at the same time with MongoDB? Is it Possible?
- MongoDB Indexes - Is it possible to create both normal & compound at the same time?
- How is it possible to enter multiple MySQL statements on a single line?
- Is it possible to have multiple try blocks with only one catch block in java?
- Which MongoDB query finds same value multiple times in an array?
- How to add a number to a current value in MySQL (multiple times at the same time)?
- How to update multiple documents in MongoDB?
- Is it possible to change the HTML content in JavaScript?
- Is it possible to synchronize the string type in Java?

Advertisements