

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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" }
- Related Questions & Answers
- MongoDB Aggregate to limit the number of records
- MySQL query to insert multiple records quickly
- How to query MongoDB with a LIMIT?
- MongoDB query to limit the returning values of a field?
- In MongoDB will limit() increase query speed?
- Insert multiple rows from another table but the inserted records should be distinct
- Get a count of total documents with MongoDB while using limit?
- MongoDB query to limit subdocuments having the given fields of the 'projection'
- MongoDB query to count records on the basis of matching criteria
- MongoDB Query to select records having a given key?
- MongoDB query to find records with keys containing dots?
- MongoDB query to get date records in a range
- Is there a way to limit the number of records in a certain MongoDB collection?
- Insert records in MongoDB collection if it does not exist?
- MongoDB query to insert an array element with a condition?
Advertisements