
- 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
Push and slice multiple times in MongoDB?
To push and slice in MongoDB, use $push and $slice. Let us create a collection with documents −
> db.demo656.insertOne({Name:"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea060264deddd72997713cf") }
Display all documents from a collection with the help of find() method −
> db.demo656.find();
This will produce the following output −
{ "_id" : ObjectId("5ea060264deddd72997713cf"), "Name" : "John" }
Here is the query to push and slice in MongoDB−
> db.demo656.update({Name:"John"}, {"$push":{"ListOfName": {"$each": ["John"], "$slice": -9}}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo656.find();
This will produce the following output −
{ "_id" : ObjectId("5ea060264deddd72997713cf"), "Name" : "John", "ListOfName" : [ "John" ] }
Following is the query to push and slice once again −
> db.demo656.update({Name:"John"}, {"$push":{"ListOfName": {"$each": ["David"], "$slice": -9}}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo656.find();
This will produce the following output −
{ "_id" : ObjectId("5ea060264deddd72997713cf"), "Name" : "John", "ListOfName" : [ "John", "David" ] }
- Related Questions & Answers
- MongoDB Limit fields and slice projection together?
- MongoDB $push in nested array?
- Work with $push in MongoDB
- Which MongoDB query finds same value multiple times in an array?
- MongoDB slice array in populated field?
- Set MongoDB $slice with a range?
- What kind of MongoDB query finds same value multiple times in an array?
- Implement MongoDB $push in embedded document array?
- How to push an array in MongoDB?
- Updating an array with $push in MongoDB
- MongoDB Aggregation to slice array inside array
- How do I $set and $push in single update with MongoDB?
- Query an array of embedded documents in MongoDB and push another?
- Push query results into variable with MongoDB?
- Cannot push into an array from MongoDB?
Advertisements