mongoDB的使用

#一.【连接Mongo】
import pymongo
#方法一
client = pymongo.MongoClient(host='localhost', port=27017)
#方法二
client = MongoClient('mongodb://localhost:27017/')

#二.【连接mongo指定数据库’test ‘】:
#方法一
db = client.test
#方法二
db = client['test']

#三.【连接指定集合(Collection)如:students】
#方法一
collection = db.students
#方法二
collection = db['students']


#四.【插入数据,在students内,用字典】
student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
result = collection.insert(student)
print(result)

'''
在 MongoDB 中,每条数据其实都有一个 _id 属性来唯一标识,如果没有显式指明 _id,MongoDB 会自动产生一个 ObjectId 类型的 _id 属性。insert() 方法会在执行后返回的 _id 值:
5932a68615c2606814c91f3d
'''

#【插入多个字典数据,用列表把字典组合】:
student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}

result = collection.insert([student1, student2])
print(result)
'''
返回的结果是对应的 _id 的集合,运行结果:
[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]
'''

'''
实际上在 PyMongo 3.X 版本中,insert() 方法官方已经不推荐使用了,当然继续使用也没有什么问题,官方推荐使用 insert_one() 和 insert_many() 方法将插入单条和多条记录分开
'''
# 【insert_one()
student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

result = collection.insert_one(student)
print(result)
print(result.inserted_id)
'''
运行结果:
<pymongo.results.InsertOneResult object at 0x10d68b558>
5932ab0f15c2606f0c1cf6c5
返回结果和 insert() 方法不同,这次返回的是InsertOneResult 对象,我们可以调用其 inserted_id 属性获取 _id
'''

#【 insert_many() 方法,我们可以将数据以列表形式传递即可
student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}

result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)
'''
insert_many() 方法返回的类型是 InsertManyResult,调用inserted_ids 属性可以获取插入数据的 _id 列表,运行结果:
<pymongo.results.InsertManyResult object at 0x101dea558>
[ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]
'''
原文地址:https://www.cnblogs.com/chenxi188/p/10572624.html