MongoDB - How to insert document into collection

We had seen an example in the earlier post about inserting document to collections i.e. move keys & values to a variable and execute insert function e.g. db.customer.insert(x)

In this post, we will see some additional examples and about Batch insert as well.
db.customers.insert({"Name" : "ABC", age " 32})

A basic insert would add single document along with "_id" is listed below -
> db.customers.find()
Output:
{
        "_id" : ObjectId("591899d3768edf8898da8c46"),
        "name" : "ABC",
        "age" : 32,
        "sex" : "male"
}

Suppose we need to multiple documents n the shell you can try the below script
db.customer.insert ([{"Name" : "ABC","age": 32},{"Name" : "DEF","age":33},{"Name" : "GHI"}])
Output:
> db.customer.find()
{ "_id" : ObjectId("59189ea4768edf8898da8c4a"), "Name" : "ABC", "age" : 32 }
{ "_id" : ObjectId("59189ea4768edf8898da8c4b"), "Name" : "DEF", "age" : 33 }
{ "_id" : ObjectId("59189ea4768edf8898da8c4c"), "Name" : "GHI" }

Notice the difference in collection names - customers & customer. If a collection does not exist, a new collection is created and documents are inserted.
Also, MongoDB is case sensitive i.e. Customer and customer are different collections.

MongoDB perform very minimal validation on the data i.e. its almost no validation at all.

Popular posts from this blog

PF2XLS - Python

Stock Analysis - Example with Ashok Leyland

Python on IBM i