- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to insert but limit the total records
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" }
Advertisements