

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 ] } ] }
- Related Questions & Answers
- Replace an array field value with MongoDB?
- MongoDB query to replace value in an array?
- Increment value of an array element with array object in MongoDB
- Check for duplicates in an array in MongoDB?
- Query an array in MongoDB to fetch a specific value
- MongoDB $addToSet to add a deep nested array of object?
- MongoDB query for Partial Object in an array
- How to append an item into a JavaScript array?
- MongoDB syntax for updating an object inside an array within a document?
- MongoDB query for capped sub-collection in an array
- How to append to array in MongoDB?
- Implement array match in MongoDB?
- Increment a property value of an element in array object with MongoDB
- Search for partial value match in an Array in PHP
- Min and max values of an array in MongoDB?
Advertisements