Is it possible to use MongoDB capped collection?


Yes, you can use capped. Capped collections are fixed-size collections that support high-throughput operations that insert and retrieve documents based on insertion order.

Let us create a collection with documents and set capped while creating a collection i.e. fixed-size collection −

> db.createCollection("demo539", { capped : true, size :100, max : 4 } );
{ "ok" : 1 }
>
>
> db.demo539.insertOne({"Name":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c9094ef4dcbee04fbbc09")
}
> db.demo539.insertOne({"Name":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c9098ef4dcbee04fbbc0a")
}
> db.demo539.insertOne({"Name":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c909bef4dcbee04fbbc0b")
}
> db.demo539.insertOne({"Name":"Sam"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c909eef4dcbee04fbbc0c")
}
> db.demo539.insertOne({"Name":"Carol"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c90a4ef4dcbee04fbbc0d")
}

Display all documents from a collection with the help of find() method −

> db.demo539.find();

This will produce the following output −

{ "_id" : ObjectId("5e8c9098ef4dcbee04fbbc0a"), "Name" : "David" }
{ "_id" : ObjectId("5e8c909bef4dcbee04fbbc0b"), "Name" : "Bob" }
{ "_id" : ObjectId("5e8c909eef4dcbee04fbbc0c"), "Name" : "Sam" }
{ "_id" : ObjectId("5e8c90a4ef4dcbee04fbbc0d"), "Name" : "Carol" }

Updated on: 14-May-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements