import pymongo
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.haha # 创建一个数据库、或者连接数据库
posts = db.posts # 创建一个collections/或者连接collections
# 打印数据库中所有的collection(集合)
print(db.collection_names(include_system_collections=False))
# 参考数据
import datetime
post = {"author": "鹏飞",
"text": "欢迎来'pengfei.ga'学习",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
#向collection中插入数据
post_id = posts.insert_one(post).inserted_id
print(post_id)
插入多条数据
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
#查询一条数据
data = posts.find_one()
pprint(data)
#条件查询
i= posts.find_one({"author": "鹏飞"})
pprint(i)
#空查询
p = posts.find_one({"author": "Eliot"})
pprint(p) # 返回None
#根据id查询
a = posts.find_one({"_id": post_id})
print(a)
student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
collection = db.collection
# result = collection.insert(student)
# print(result)
#
result = collection.insert([student1, student2])
print(result)
data = collection.find()
for f in data:
print(f)
student = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
result = collection.insert_one(student)
print(result)
print(result.inserted_id)
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)
result = collection.find({'name': 'Mike'})
print(type(result))
print(result)
for i in result:
print(i)
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('5d10705b22578728221bfcc2')})
print(result)
results = collection.find().sort('name', pymongo.ASCENDING) # pymongo.ASCENDING指定升序 #pymongo.DESCENDING 表示降序
print([result['name'] for result in results])
# condition = {'name': 'Mike'}
# student = collection.find_one(condition)
# print(student)
# student['age'] = 25
# result = collection.update(condition, student)
# print(result)
result = collection.remove({'name': 'Jordan'})
print(result)
mongo数据的操作
最新推荐文章于 2023-12-29 15:15:08 发布