java - Mongodb $slice operator with Mongotemplate -


my document below :

{     "_id" : objectid("53b246aae4b0ad1d6b6a5c02"),             "name" : "pathology",          "status" : true,     "history" : [          {             "updateby" : "53bcc05a48d1665cd8692993",                         "date" : isodate("2014-12-20t10:19:07.246z")         }     ] } 

i want maintain last 5 histories in history key :

so can write following query that:

db.collection.update(      { "_id" : objectid("53b246aae4b0ad1d6b6a5c02") },     { $push : {          history :              {               $each : [                       {                         "updateby" : "53bcc05a48d1665cd8692993",                                               "date" : new date()                      }                 ] ,                $slice : -5              }         }      }  ); 

but don't know how write update query in mongotemplate $slice, $each , $push.

as @christophstrobl pointed out in comment

$slice not yet supported update in spring-data-mongodb. please vote datamongo-832

you need devise workaround utilises mongotemplate's executecommand method, providing json string findandmodify command:

public class foorepositoryimpl implements foorepositorycustom {      @autowired     protected mongotemplate mongotemplate;      public void pushhistory(string objectid, string userid) {         date = new date();         basicdbobject searchquery = new basicdbobject().append("id", objectid);         dbobject modifiedobject = new basicdbobject();         list<dbobject> eachobjectlist = new arraylist<dbobject>();          dbobject object = new basicdbobject().append("updateby", userid);         object.append("date", now);         eachobjectlist.add(object);          modifiedobject.put("$push",              new basicdbobject().append("history",                      new basicdbobject().append("$each", eachobjectlist)                 ).append("$slice", -3)             );          string json = "{ findandmodify: \"collectionname\", query: " + searchquery.tostring() + ", update: " + modifiedobject.tostring();          try {             mongotemplate.executecommand(json);         } catch (exception e) {             system.out.println(e);         }     } } 

Comments