首页 文章

Spring Data MongoDB中的Capped数组

提问于
浏览
1

我'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'已经看过其他帖子,但它没有使用 spring 数据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方法后,我可以看到附加的新分数,并且它的大小超过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>

希望听到您的意见和建议 .

1 回答

  • 0

    您可以将更新更改为以下内容:

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

    spring 数据尚不支持 $slice push - > https://jira.spring.io/browse/DATAMONGO-832

相关问题