Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a capped collection with Spring Data? - MongoDB

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

like image 803
KCOtzen Avatar asked Feb 22 '23 14:02

KCOtzen


2 Answers

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.

like image 82
Oliver Drotbohm Avatar answered Feb 25 '23 18:02

Oliver Drotbohm


CollectionOptions options = new CollectionOptions(null, 5000, true) is now deprecated. Instead you should use the following code:

CollectionOptions options = CollectionOptions.empty()
                    .capped().size(5242880)
                    .maxDocuments(5000)

Don't forget to specify the size. For more info see Tailable Cursors.

like image 26
Tombery Avatar answered Feb 25 '23 16:02

Tombery