当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Capped Array in Spring Data MongoDB

问题描述:

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);

}

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: