I'm new to Spring Data MongoDB and wondering if you could help me. Basically, what I want to achieve is to limit the size of an embedded array in my document. I've seen other post but it's not using the spring data mongodb ( Saving with Java springdata a mongoDB document with capped array ($slice and $sort) , MongoDB 2.4's "Limit Number of Elements in an Array after an Update" using C# driver? ).
Sample Document:
{
_id: 1,
scores: [
{ attempt: 1, score: 10 },
{ attempt: 2 , score:8 }
]
}
updateScore() { Query query = new Query(Criteria.where("id").is(id)); query.fields().slice("scores", -3); Update update = new Update(); update.push("scores", scores); mongoOperations.findAndModify(query, update, MyDocument.class); }
updateScore() { Query query = new Query(Criteria.where("id").is(id)); query.fields().slice("scores", -3); Update update = new Update(); update.push("scores", scores); mongoOperations.findAndModify(query, update, MyDocument.class); }
After calling updateScore method, I could see that new scores were appended and it's size exceeds 3.
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.0</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
Hope to hear your comments and suggestion.
You could change your update to something like this:
Query query = new Query(Criteria.where("id").is(id));
query.fields().slice("scores", -3);
Update update = new Update();
update.push("scores", scores);
update.push("scores", new BasicDBObject("$each", scores).append("$slice", -3));
mongoOperations.findAndModify(query, update, MyDocument.class);
$slice within within a push is not yet supported by spring-data -> https://jira.spring.io/browse/DATAMONGO-832
update.push("scores").slice(-3).each(scores)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.