mongo数据的操作

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值