2

我的文件如下:

{
    "_id" : ObjectId("53b246aae4b0ad1d6b6a5c02"),        
    "name" : "PATHOLOGY",     
    "status" : true,
    "history" : [ 
        {
            "updateBy" : "53bcc05a48d1665cd8692993",            
            "date" : ISODate("2014-12-20T10:19:07.246Z")
        }
    ]
}

我想在historykey 中保留最后 5 个历史记录:

所以我可以为此编写以下查询:

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

但我不知道如何用,和编写update查询。MongoTemplate$slice$each$push

4

1 回答 1

0

正如@ChristophStrobl在他们的评论中指出的那样

$slicespring-data-mongodb 中的 Update 尚不支持。请投票给DATAMONGO-832

您需要设计一种利用 mongoTemplate 的方法的解决executeCommand方法,为 json 字符串提供以下findAndModify命令:

public class FooRepositoryImpl implements FooRepositoryCustom {

    @Autowired
    protected MongoTemplate mongoTemplate;

    public void pushHistory(String objectId, String userId) {
        Date now = 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);
        }
    }
}
于 2016-01-29T09:29:38.290 回答