Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement MongoDB $addToSet for an array in an array and append a value
For this, use update() along with $addToSet. The $addToSet operator adds value to an array unless the value is already present, in which case $addToSet does nothing to that array. Let us create a collection with documents −
> db.demo509.insertOne(
... {
...
... "value1" : [
... {
... "value2" : [
... 76,
... 14,
... 56
... ]
... },
... {
...
... "value2" : [
... 12,
... 19,
... 91
... ]
... },
... {
...
... "value2" : [
... 87
... ]
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e88421d987b6e0e9d18f57d")
}
Display all documents from a collection with the help of find() method −
> db.demo509.find();
This will produce the following output −
{ "_id" : ObjectId("5e88421d987b6e0e9d18f57d"), "value1" : [
{ "value2" : [ 76, 14, 56 ] },
{ "value2" : [ 12, 19, 91 ] }, { "value2" : [ 87 ] }
] }
Following is the query to implement $addToSet and append in an array −
> db.demo509.update({},{$addToSet:{"value1.2.value2":1000}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo509.find();
This will produce the following output −
{ "_id" : ObjectId("5e88421d987b6e0e9d18f57d"), "value1" : [
{ "value2" : [ 76, 14, 56 ] },
{ "value2" : [ 12, 19, 91 ] }, { "value2" : [ 87, 1000 ] }
] }Advertisements