Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to insert but limit the total records
To insert documents while limiting the total records in a MongoDB collection, use capped collections with the capped: true option and set the max parameter to define the maximum number of documents.
Syntax
db.createCollection("collectionName", {
capped: true,
size: sizeInBytes,
max: maxDocuments
});
Create Capped Collection
Let us create a capped collection that allows a maximum of 4 documents ?
db.createCollection("demo297", {capped: true, size: 4, max: 4});
{ "ok" : 1 }
Insert Documents
Now insert 5 documents to see how the collection maintains the limit ?
db.demo297.insertMany([
{"Name": "Chris"},
{"Name": "Bob"},
{"Name": "Mike"},
{"Name": "Sam"},
{"Name": "John"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e4d54385d93261e4bc9ea43"),
ObjectId("5e4d543e5d93261e4bc9ea44"),
ObjectId("5e4d543e5d93261e4bc9ea45"),
ObjectId("5e4d543f5d93261e4bc9ea46"),
ObjectId("5e4d54405d93261e4bc9ea47")
]
}
Verify Result
Display all documents to see which records remain ?
db.demo297.find();
{ "_id" : ObjectId("5e4d543e5d93261e4bc9ea44"), "Name" : "Bob" }
{ "_id" : ObjectId("5e4d543e5d93261e4bc9ea45"), "Name" : "Mike" }
{ "_id" : ObjectId("5e4d543f5d93261e4bc9ea46"), "Name" : "Sam" }
{ "_id" : ObjectId("5e4d54405d93261e4bc9ea47"), "Name" : "John" }
Key Points
- Capped collections automatically remove the oldest documents when the limit is exceeded.
- The
sizeparameter sets storage space in bytes (minimum 4096 bytes). - The
maxparameter limits the total number of documents. - Documents maintain insertion order and cannot be updated to increase size.
Conclusion
Capped collections provide an automatic way to limit total records by removing the oldest documents when limits are exceeded. This is useful for log collections or any scenario requiring a fixed-size data store.
Advertisements
