# 插入文档
# Documents, Data in MongoDB is represented (and stored) using JSON-style documents.
# In PyMongo we use dictionaries to represent documents.
# As an example, the following dictionary might be used to represent a blog post:
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
students = [
{
'id': '20160101',
'name': 'Marco',
'age': 21,
'gender': 'male'
},
{
'id': '20160101',
'name': 'Lilei',
'age': 22,
'gender': 'male'
}
]
# Inserting a document to collection
result = collection.insert_one(student1)
# Inserting many documents to collection
result = collection.insert_many(students)
# 查询文档数据
# Getting a Single Document With find_one()
print(collection.find_one())
# Search document with key word for a single document
print(collection.find_one({'name':'Lilei'}))
# Querying for More Than One Document:
# To get more than a single document as the result of a query we use the find() method.
# find() returns a Cursor instance, which allows us to iterate over all matching documents.
# For example, we can iterate over every document in the posts collection:
print(collection.find())
for item in collection.find():
print(item)
# 范围查询
# MongoDB supports many different types of advanced queries.
# As an example, lets perform a query where we limit results to the students who is older than 20, but also sort the results by name:
for item in collection.find({"age":{"$gt":20}}):
print(item)
# 正则表达式查询
for item in collection.find({'name': {'$regex': '^J.*'}}):
print(item)
# 查找计数
# If we just want to know how many documents match a query we can perform a count() operation instead of a full query.
# We can get a count of all of the documents in a collection
print(collection.find().count())
print(collection.find({'name':'Lilei'}).count())
# 排序
# 使用sort()函数进行排序,函数中可以指定参数: pymongo.ASCENDING 指定升序,或者pymongo.DESCENDING降序。
for item in collection.find({"age":{"$gt":20}}).sort('name',pymongo.ASCENDING):
print(item)
# 偏移与限制查询个数
# skip(n):忽略查询出来的前n个结果,从n+1结果开始算起
for item in collection.find({"age":{"$gt":20}}).sort('name').skip(1):
print(item)
# limit(n):只取查询出来的前n个结果
for item in collection.find({"age":{"$gt":20}}).sort('name').skip(1).limit(1):
print(item)