pythonとMongoDBのインタラクション
3769 ワード
eg:
import pymongo
from pymongo.results import DeleteResult
from bson.objectid import ObjectId
#
''''
# host=None, : IP 127.0.0.1
# port=None, : 27017
# '''
mongo_client = pymongo.MongoClient(
host = '127.0.0.1',port=27017
)
# mongo_client = pymongo.MongoClient(
# 'mongodb://127.0.0.1:27017/'
# )
#
# mongo_client = pymongo.MongoClient(
# 'mongodb://username:password@ip:port'
# )
#
db = mongo_client['mongotest']
# db = mongo_client.mongotest
#
col_name = db['test']
#
# def insert_data():
# document1 = {
# 'title': 'zhangzengrui',
# 'actors': ' ',
# 'tags': ' 1',
# 'info': ' 1',
# 'age': 12
# }
# document2 = {
# 'title': 'zhangzengrui',
# 'actors': ' ',
# 'tags': ' 1',
# 'info': ' 1',
# 'age': 15
# }
# document3 = {
# 'title': 'zhangzengrui',
# 'actors': ' ',
# 'tags': ' 1',
# 'info': ' 1',
# 'age': 18
# }
# result = col_name.insert(document1)
# result = col_name.insert([document1,document2,document3])
# result = col_name.insert_many([document1,document2])
# print(result)
# def update_data():
# multi False
# upsert = False, , True
# result = col_name.update(
# # {'title': ' 3'},
# # {'$set': {'info': '1712B'}}
# # )
# # print(result)
# multi False
# result = col_name.update(
# {'title': ' 3'},
# {'name': ' ','gender': ' ','age': 18}
# )
# print(result)
# result = col_name.update_one(
# {'name': ' '},
# {'$set': {'age':20,'class':'1712B'}}
# )
# print(result)
# col_name.update_many()
# save
# result = col_name.save(
# {'_id': 'ObjectId("5c25e77bfd2c4f1de07b6c81")',
# 'title': ' ', 'info': '1712B', 'age': 20}
# )
# ID
# result = col_name.save(
# {'_id': '1234567890',
# 'title': ' ', 'info': '1712B', 'age': 20}
# )
# print(result)
def find_data():
#
# result = col_name.find({})
#
# result = col_name.find({'name': ' '})
# print([i for i in result])
#
# result = col_name.find_one({'name': ' 1'})
# print(result)
# limit :
# skip ;
# sort: 1:
result = col_name.find({}).skip(2).limit(3).sort('age',1)
#
result = col_name.find({}).skip(2).limit(3).sort([('age',1),('year',1)])
for i in result:
print(i)
#
# def delete_data():
# # multi True
# #
# result = col_name.remove({'title': ' 1'}, multi=False)
# print(result)
# #
# result = col_name.delete_one({'title': ' 2'})
# print(result)
# #
# result = col_name.delete_many({'title': ' 1'})
# print(result.deleted_count())
if __name__ == '__main__':
# insert_data()
# delete_data()
# update_data()
find_data()