Download our e-book of Introduction To Python
Neha Kumawat
2 years ago
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
> use mydatabase
switched to db mydatabase
> db.createCollection("Demo")
{ "ok" : 1 }
> document = {"name": "Sham", "age": "25", "city": "Pune"}
{ "name": "Sahm", "age": "25", "city": "Pune" }
> db.sample.insert(document)
WriteResult({ "nInserted" : 1 })
>
use demoDB
switched to db demoDB
> db.createCollection("demo")
{ "ok" : 1 }
> data = [
{"_id": "1", "name": "Amar", "age": "21", "city": "Pune"},
{"_id": "2", "name" : "Akbar", "age" : 23, "city" : "Hydrabad" },
{"_id": "3", "name" : "Anthani", "age" : 25, "city" : "Mumbai" }
]
[
{"_id": "1", "name": "Amar", "age": "21", "city": "Pune"},
{"_id": "2", "name" : "Akbar", "age" : 23, "city" : "Hydrabad" },
{"_id": "3", "name" : "Anthani", "age" : 25, "city" : "Mumbai" }
]
> db.demo.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
coll = db['example']
#Inserting document into a collection
doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
coll.insert_one(doc1)
print(coll.find_one())
{'_id': ObjectId('5d63ac6ce043e2a93775858b'), 'name': 'Sham', 'age': '25', 'city': 'Pune'}
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
coll = db['example']
#Inserting document into a collection
data = [
{"_id": "1", "name": "Amar", "age": "21", "city": "Pune"},
{"_id": "2", "name" : "Akbar", "age" : 23, "city" : "Hydrabad" },
{"_id": "3", "name" : "Anthani", "age" : 25, "city" : "Mumbai" }
]
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
Data inserted ......
['1', '2', '3']