How to Create a capped collection with Spring Data

2019-04-02 08:00发布

I'm working on a simple project. I'm using SpringData and MongoDB.

Everything is perfect creating normal collections, but now I have to register information, I mean a logging functionality.

So I read this in the mongo documentation:

Capped collections provide a high-performance means for storing logging documents in the database. Inserting objects in an unindexed capped collection will be close to the speed of logging to a filesystem. Additionally, with the built-in FIFO mechanism, you are not at risk of using excessive disk space for the logging.

I thought great! this is what I need, but I have a doubt. Is posible to create this kind of collections with SpringData??? I couldn't find anything in SpringData documentation.

Someone knows something about this?

Thanks

3条回答
老娘就宠你
2楼-- · 2019-04-02 08:10

If you have collection created by spring-data (for example: reservation), you can easily convert it to capped, just like so:

db.runCommand({ convertToCapped: 'reservation', size: 9128 })

read mongodb manual: https://docs.mongodb.com/manual/reference/command/convertToCapped/

ps: @Tailable annotation is very sexy, it can help you track updates for that collection and react on it changes using reactive programming principles

查看更多
叛逆
3楼-- · 2019-04-02 08:15

Using CollectionOptions options = new CollectionOptions(null, 5000, true) is deprecated now.

Use CollectionOptions options = CollectionOptions.empty().capped().size(5242880).maxDocuments(5000) instead. Don't forget to specify the size.

Everything is explained here in the documentation: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#tailable-cursors

查看更多
Luminary・发光体
4楼-- · 2019-04-02 08:36

There's a method createCollection(…) taking a CollectionOptions argument where you can specify a collection to be capped:

// The 'true' is setting it to capped
CollectionOptions options = new CollectionOptions(null, 50, true);
mongoOperations.createCollection("myCollection", options);

Might be a good idea to have those options exposed to the @Document annotation to automatically take care of them when building the mapping context but we generally got the feedback of people wanting to manually handle those collection setup and indexing operations without too much automagic behavior. Feel free to open a JIRA in case you'd like to see that supported nevertheless.

查看更多
登录 后发表回答