Push and slice multiple times in MongoDB?

MongoDBDatabaseBig Data Analytics

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" ] }
raja
Published on 13-May-2020 12:45:32
Advertisements