简体   繁体   English

Spring Data MongoDB 中的上限数组

[英]Capped Array in Spring Data MongoDB

I'm new to Spring Data MongoDB and wondering if you could help me.我是 Spring Data MongoDB 的新手,想知道您是否可以帮助我。 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? ).我看过其他帖子,但它没有使用 spring 数据 mongodb( 使用 Java springdata 保存带有上限数组($slice 和 $sort)的 mongoDB 文档MongoDB 2.4 的“更新后数组中的元素数量限制”使用C# 驱动程序? )。

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. 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方法后,我可以看到,新的分数附加,它的大小超过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 spring-data 尚不支持推送中的$slice -> https://jira.spring.io/browse/DATAMONGO-832

update.push("scores").slice(-3).each(scores)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM