The limit operator in MongoDB is used to limit the number of documents that a query returns. It is very useful in scenarios where you only need a certain number of documents from a big collection.
Here’s how you can use the limit operator in MongoDB. Let’s say, we have a collection called “students”, and you want to get only the first 5 students.
1. Using MongoDB’s shell:
\`\`\`javascript db.students.find().limit(5) \`\`\`1. Using Node.js MongoDB Driver:
\`\`\`javascript const MongoClient = require(‘mongodb’).MongoClient; const url = ‘mongodb://localhost:27017’; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db(“mydb”); dbo.collection(“students”).find().limit(5).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }); \`\`\`Just replace “students” with the name of your collection, and 5 with the number of documents you want to get.
One thing to note, the documents returned by the find() method are sorted by the \_id field, if you want to sort the documents by another field, you should use sort() method. Take a look at the example below:
```
db.students.find().sort({name: 1}).limit(5)
```
In this example, documents will be sorted by the ‘name’ field in ascending order before the ‘limit’ method is applied.