+91 81900 98289

MongoDB Limit

This MongoDB Limit lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

limit stops the cursor after a number of documents. Combine it with sort when you want the first page of an ordered result.

skip jumps ahead. Large skips are slow on a big collection.

Example 1: Start here

find().limit(2) returns two documents.

collection = [{"id": n} for n in range(1, 6)] # a list; the values stay in this order print(collection[:2])

Example 2: Filter the rows

MongoDB Limit is easier to see as a list of records. The filter keeps every row whose seats value is at least 10.

rows = [{"topic": "MongoDB Limit", "seats": 21}, {"topic": "SQL", "seats": 12}] # a list; the values stay in this order print([row["topic"] for row in rows if row["seats"] >= 10]) # keep the items that pass the test

Example 3: Update one field

An update changes one field and leaves the rest of the record alone. On a database you would run an UPDATE or an update_one for the same change.

row = {"topic": "MongoDB Limit", "seats": 21} # a dictionary; each key has one value row["seats"] = row["seats"] + 1 # change this one field print(row)

Example 4: Count the matches

Counting matches is the idea behind COUNT(*). Here the number 21 appears twice.

rows = [21, 4, 21] # a list; the values stay in this order print(sum(1 for value in rows if value == 21)) # keep the items that pass the test
find().limit(2) returns two documents.
Call Now 81900 98289