Pratik Malkar
Pratik Malkar

Reputation: 25

How to delete particular no of elements from array in mongodb

I have collection as below

"_id" : "PS8720_18",
    "AlertID" : "18",
    "Status" : "ACTIVE",
    "triggerHistory" : [ 
        {"triggerId" : "1535081507421"}, 
        {"triggerId" : "1535105196735"}, 
        {"triggerId" : "1535341330335"}, 
        {"triggerId" : "1535364578821"}
 ]

I want to delete all element and just want keep last two entries in the array. Each document has different no of elements in array. How do I achieve this?

Upvotes: 1

Views: 37

Answers (1)

Nitin Bhanderi
Nitin Bhanderi

Reputation: 332

Please Check with the following Query

db.getCollection('youtablename').update({}, {
 $push: {
  triggerHistory: {
     $each: [ ],
     $slice: -2
  }
}},{multi:true})

Hope it Helps !!

Upvotes: 1

Related Questions