ray
ray

Reputation: 15227

MongoDB - conversion to capped collection results in unexpected collection size

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.

The scripts I used:

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

What I have tried:

  1. use another MongoDB v5.0.3 to verify the behaviour: same result
  2. insert some more records to see if it will return to expected 5 documents: same result
db.testCollection.insertOne({"key": 11});

db.testCollection.countDocuments(); // output: 8

db.testCollection.find(); // output: document with key from 4 to 11
  1. changing the capped collection size in v6.0.3 setup: same result
db.runCommand( { collMod: "testCollection", cappedSize: 5 } )

Any explanation for this unexpected behaviour?

Upvotes: 0

Views: 88

Answers (1)

Prashant Pokhriyal
Prashant Pokhriyal

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

Reference

Upvotes: 1

Related Questions