1

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.

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

The community encourages adding explanations alongisde code, rather than purely code-based answers (see here). Also, please have a read of this help page about how to format code properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.