Download our e-book of Introduction To Python
Shashank Shanu
4 years ago
db.COLLECTION_NAME.find().limit(NUMBER)
# using database
use my_test_DB
#creating
collection
db.createCollection("my_sample")
data = [
... {"_id":
"101", "name": "Shyam", "age":
"27", "city": "Hyderabad"},
... {"_id":
"102", "name": "Ram", "age": 28,
"city": "Bangalore"},
... {"_id":
"103", "name": "john", "age": 26,
"city": "Mumbai"},
... {"_id":
"104", "name": "Romeo", "age": 25,
"city": "Pune"},
... {"_id":
"105", "name": "Sarmista", "age": 23,
"city": "Delhi"},
... {"_id":
"106", "name": "Rasajna", "age": 26,
"city": "Chennai"}
]
#insert data
db.my_sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
db.my_sample.find().limit(3)
{ "_id" : "101", "name" : "Shyam", "age" : "27", "city" : "Hyderabad" }
{ "_id" : "102", "name" : "Ram", "age" : 28, "city" : "Bangalore" }
{ "_id" : "103", "name" : "john", "age" : 26, "city" : "Mumbai" }
from pymongo import
MongoClient
#Create a pymongo client
mo_client = MongoClient('localhost', 27017)
#Getting the database instance
database = mo_client ['l']
#Creating a collection
collection = database ['my_Collections']
#Inserting document into a collection
data = [
{"_id": "1001",
"name": "Shyam", "age": "27",
"city": "Hyderabad"},
{"_id": "1002",
"name": "Ram", "age": "28",
"city": "Bangalore"},
{"_id": "1003",
"name": "John", "age": "26",
"city": "Mumbai"},
{"_id": "1004", "name": "Romeo",
"age": 25, "city": "Pune"},
{"_id": "1005",
"name": "Sarmista", "age": 23, "city":
"Delhi"},
{"_id": "1006",
"name": "Rasajna", "age": 26, "city":
"Chennai"}
]
result = collection.insert_many(data)
print("Data inserted ......")
#Retrieving first 3 documents using the find() and limit() methods
print("First 3 documents in the collection: ")
for i in coll.find().limit(3):
print(i)
Data inserted ......
First 3 documents in the collection:
{'_id': '101', 'name': 'Shyam', 'age': '27', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Ram', 'age': '28', 'city': 'Bangalore'}
{'_id': '103', 'name': 'John', 'age': '26', 'city': 'Mumbai'}