+91 81900 98289

MongoDB Insert

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

insert_one adds one document. insert_many adds a list. MongoDB adds an _id when you do not supply one.

The example appends a document to the stand-in collection.

Example 1: Start here

On a real client the call is collection.insert_one({"name": "Meera", "track": "Python"}).

collection = [] # a list; the values stay in this order collection.append({"name": "Meera", "track": "Python"}) # add one item at the end of the list print(collection)

Example 2: Filter the rows

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

rows = [{"topic": "MongoDB Insert", "seats": 23}, {"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 Insert", "seats": 23} # 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 23 appears twice.

rows = [23, 4, 23] # a list; the values stay in this order print(sum(1 for value in rows if value == 23)) # keep the items that pass the test
On a real client the call is collection.insert_one({"name": "Meera", "track": "Python"}).
Call Now 81900 98289