
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
Delete N-th Element of Array in MongoDB
You can use $unset as well as $pull operator with an update to delete the nth element of an array.
Let us create a collection with a document. The query to create a collection with a document is as follows −
> db.getNThElementDemo.insertOne({"UserName":"John","UserAge":23,"ListOfFriends":["Carol","Sam","Mike","Bob"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c94ee7516f542d757e2b43e") } > db.getNThElementDemo.insertOne({"UserName":"David","UserAge":21,"ListOfFriends":["Chris","Robert"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c94eeaa16f542d757e2b43f") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.getNThElementDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c94ee7516f542d757e2b43e"), "UserName" : "John", "UserAge" : 23, "ListOfFriends" : [ "Carol", "Sam", "Mike", "Bob" ] } { "_id" : ObjectId("5c94eeaa16f542d757e2b43f"), "UserName" : "David", "UserAge" : 21, "ListOfFriends" : [ "Chris", "Robert" ] }
Here is the query to delete the nth element of an array −
> db.getNThElementDemo.update({}, {$unset : {"ListOfFriends.2" : 1 }}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.getNThElementDemo.update({}, {$pull : {"ListOfFriends" : null}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Now you can check nth element from an array has been removed.
The query is as follows −
> db.getNThElementDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c94ee7516f542d757e2b43e"), "UserName" : "John", "UserAge" : 23, "ListOfFriends" : [ "Carol", "Sam", "Bob" ] } { "_id" : ObjectId("5c94eeaa16f542d757e2b43f"), "UserName" : "David", "UserAge" : 21, "ListOfFriends" : [ "Chris", "Robert" ] }
Advertisements