The Usage of Pymongo

Install

pymongo document

install pymongo from the tar package download from website

python setup.y install

Usage

# import
from pymongo import MongoClient # Making a Connection with MongoClient client = MongoClient(host='127.0.0.1', port=27017) # use the MongoDB URI format: # client = MongoClient('mongodb://localhost:27017/') # getting a database
db_mark = client['mark'] # getting a collection
c_student = db_mark.student # getting all of the documents in collection c_student
students = c_student.find()
for student in students:
print(student)

Insert

The three methods to insert data to collection, obviously, insert() method is deprecated.

# Insert an iterable of documents
stu.insert_many(students) # insert is deprecated. Use insert_one or insert_many instead
stu.insert() # Insert a single document
stu.insert_one()
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

db = client['python']
# stu = db.create_collection('stu')
stu = db.stu students = [
{'name': 'jackson', 'age': 17, 'gender': 1},
{'name': 'amada', 'age': 19, 'gender': 0},
{'name': 'micheal', 'age': 23, 'gender': 1},
{'name': 'lucy', 'age': 16, 'gender': 0},
{'name': 'happy', 'age': 12, 'gender': 1},
{'name': 'java', 'age': 34, 'gender': 0},
{'name': 'python', 'age': 21, 'gender': 1},
{'name': 'ruby', 'age': 11, 'gender': 1},
] stu.insert_many(students) #stu.insert()
#stu.insert_one()

Delete

stu.delete_many()  # justOne:False
stu.delete_one() # justOne:True

Update

stu.update()
stu.update_many()
stu.update_one()

Search

find()

stu.find()
stu.find_one()
stu.find_one_and_replace()
stu.find_one_and_delete()
stu.find_one_and_update()
# show total number
stu.count()

aggregate()

In [22]: s.aggregate([{'$project':{'_id':0}}])
Out[22]: <pymongo.command_cursor.CommandCursor at 0x7efdda495a20> In [23]: ret=s.aggregate([{'$project':{'_id':0}}]) In [24]: for x in ret:
...: print(x)
...:
{'name': 'jack', 'age': 12, 'gender': 1}
{'name': 'rose', 'age': 11, 'gender': 0}
{'name': 'jackson', 'age': 17, 'gender': 1}
{'name': 'amada', 'age': 19, 'gender': 0}
{'name': 'micheal', 'age': 23, 'gender': 1}
{'name': 'lucy', 'age': 16, 'gender': 0}
{'name': 'happy', 'age': 12, 'gender': 1}

End

fatal method to serach data from mongodb database is use aggregate

上一篇:java中处理字符编码(网页与数据库)(转)


下一篇:Unity3D--学习太空射击游戏制作(一)