Python对MongoDB增删改查

pip install pymongo

import pymongo

#   建立连接
client = pymongo.MongoClient()

#   指定数据库   (不存在则会新建)
db = client['py_mongo']
#   删除数据库
# client.drop_database('py_mongo_temp')


#   创建集合
# db.create_collection('col_temp')
#   删除集合
# print(db.drop_collection('col_temp'))
#   指定集合     (不存在则会新建)
collection = db['mongo_col']

# collection = pymongo.MongoClient()['py_mongo']['mongo_col']

基本使用:insert() remove() update() find()

#   增   insert()
#   如果不指定_id参数,MongoDB会为文档分配一个唯一的ObjectId
#   增加一条
# collection.insert({'_id':1,'name':'JiYu','num':0})
#   增加多条
# collection.insert(  [
#     {'name':'jiyu','num':12},
#     {'name':'jiyu','num':34},
#     {'name':'nianhua','num':12},
#     {'name':'nianhua','num':34},
# ]   )


#   删   remove()
#   删除集合中满足条件的所有文档
# collection.remove({'name':'jiyu'})
#   只删除集合中满足条件的第一条文档
# collection.remove({'name':'nianhua'},multi=False)
#   删除所有
# collection.remove()


#   改   update()
#   修改一条数据  只有name,没有num了,整条数据变成<update>里的内容
# collection.update({'name':'jiyu'},{'name':'nianhua'})
#   指定属性修改  $set
# collection.update({'name':'jiyu'},{'$set':{'name':'nianhua'}})
#   修改集合中所有满足条件的文档:multi: true
# collection.update({'name':'nianhua'},{'$set':{'name':'NianHua'}},multi=True)


#   查   find()
#   查询所有
# for i in collection.find():
#     print(i)
#   根据条件查询
# for i in collection.find({'name': 'NianHua'}):
#     print(i)
#   and 和 or 条件
# condition = {'$or': [{'num': 12}, {'name': 'NianHua'}]}
# for i in collection.find(condition):
#     print(i)
#   操作符
# for i in collection.find({'num': {'$gt': 20}}):
#     print(i)

官方推荐:insert_one() delete_one() update_one() find_one()

#   增   insert_one()    insert_many()
#   添加一条
# collection.insert_one({'name':'ming','num':101})
#   添加多条
# collection.insert_many( [
#     {'name':'hong','num':111},
#     {'name':'fei','num':111}
# ] )


#   删   delete_one()    delete_many()
#   删除一条
# collection.delete_one({'num': 111})
#   删除多条
# collection.delete_many({'name':'NianHua'})

#   改   update_one()    update_many()
#   需要用$进行操作,加上$set,否则会报错:update only works with $ operators
#   修改一条
# collection.update_one({'name':'jiyu'},{'$set':{'num':99}})
#   修改多条
# collection.update_many({'name':'jiyu'},{'$set':{'num':99}})


#   查   find_one()      find()
#   查一条
# print(collection.find_one({'num':111}))
#   查找所有        find() 只是一个对象 用for 遍历出来
for i in collection.find():
    print(i)

相关推荐