MongoDB query to insert but limit the total records

MongoDBDatabaseBig Data Analytics

To insert and limit the total records while inserting, use capped:true and set the size and max values.

Let us create a collection with documents wherein we have set capped:true and size to 4 −

> db.createCollection("demo297", {capped:true, size:4,max:4});
{ "ok" : 1 }
> db.demo297.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d54385d93261e4bc9ea43")
}
> db.demo297.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d543e5d93261e4bc9ea44")
}
> db.demo297.insertOne({"Name":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4d543e5d93261e4bc9ea45")
}
> db.demo297.insertOne({"Name":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d543f5d93261e4bc9ea46")
}
> db.demo297.insertOne({"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4d54405d93261e4bc9ea47")
}

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

> db.demo297.find();

This will produce the following output −

{ "_id" : ObjectId("5e4d543e5d93261e4bc9ea44"), "Name" : "Bob" }
{ "_id" : ObjectId("5e4d543e5d93261e4bc9ea45"), "Name" : "Mike" }
{ "_id" : ObjectId("5e4d543f5d93261e4bc9ea46"), "Name" : "Sam" }
{ "_id" : ObjectId("5e4d54405d93261e4bc9ea47"), "Name" : "John" }
raja
Published on 01-Apr-2020 07:18:37
Advertisements