Reputation: 15227
I have a MongoDB v6.0.3 setup. I am trying to convert a normal, prepopulated collection (with 10 documents) into a capped collection of size 5.
db.testCollection.drop();
db.testCollection.insertMany([
{"key": 1},
{"key": 2},
{"key": 3},
{"key": 4},
{"key": 5},
{"key": 6},
{"key": 7},
{"key": 8},
{"key": 9},
{"key": 10},
]);
db.runCommand({"convertToCapped": "testCollection", size: 5});
But when I am verifying the result, I get an output of 8 documents instead of the expected 5 documents:
db.testCollection.countDocuments(); // output: 8
db.testCollection.find(); // output: document with key from 3 to 10
db.testCollection.insertOne({"key": 11});
db.testCollection.countDocuments(); // output: 8
db.testCollection.find(); // output: document with key from 4 to 11
db.runCommand( { collMod: "testCollection", cappedSize: 5 } )
Any explanation for this unexpected behaviour?
Upvotes: 0
Views: 88
Reputation: 3827
The size
field represents the maximum size of the collection in bytes, which MongoDB will pre-allocate for the collection. If the size field is less than or equal to 4096, then the collection will have a cap of 4096 bytes. Otherwise, MongoDB will raise the provided size to make it an integer multiple of 256.
In your case you should use max
field which specifies a maximum number of documents for the collection.
Note
The size argument is always required, even when you specify max number of documents. MongoDB will remove older documents if a collection reaches the maximum size limit before it reaches the maximum document count.
You query should be somewhat like below:
If you want to create a new capped collection.
db.createCollection("testCollection", { capped: true, size: 4096, max: 5 })
If you want to convert a collection to capped.
db.runCommand({"convertToCapped": "testCollection", size: 4096, max: 5});
If you want to change a capped collection's size.
db.runCommand( { collMod: "testCollection", cappedSize: 4096 } )
If you want to change the maximum number of documents in a capped collection.
db.runCommand( { collMod: "testCollection", cappedMax: 5} )
Note
Queries are supported in Mongodb version 6.0
Upvotes: 1