python执行mongo命令_使用Python操作mongodb数据库

安装MongoDB

启动mongodb服务命令:

mongod --dbpath C:\software\mongodb\data\db

其中, dbpath 后面的参数是安装的 mongodb 下面创建的目录路径

连接MongoDB

安装 pymongo 库

pip3 install pymongo

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)

另外一种写法

client = pymongo.MongoClient('mongodb://localhost:27017/')

指定数据库

db = client.test

或者:

db = client['test']

指定集合

collection = db.student

操作mongodb

插入数据

student = {

'id': '20170101',

'name': 'Jordan',

'age': 20,

'gender': 'male'

}

result = collection.insert_one(student)

print(result)

同时插入多条数据

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)

查询数据

result = collection.find_one({'name':'Mike'})

print(type(result))

print(result)

{'_id': ObjectId('5edf58cc4f42c847b642b755'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

可以发现,它多了 _id 属性,这就是 MongoDB 在插入过程中自动添加的。

此外,我们也可以根据 ObjectId 来查询,此时需要调用 bson 库里面的 objectid:

from bson.objectid import ObjectId

result = collection.find_one({'_id':ObjectId('5edf58cc4f42c847b642b755')}) print(result)

多条数据查询

results = collection.find({'age':20})

for result in results:

print(result)

{'_id': ObjectId('5edf587b4f42c847b642b753'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}

{'_id': ObjectId('5edf58cc4f42c847b642b754'), 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}

查询年龄大于20的数据

results = collection.find({'age': {'$gt':20}})

for result in results:

print(result)

{'_id': ObjectId('5edf58cc4f42c847b642b755'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

正则匹配

results = collection.find({'name': {'$regex': '^M.*'}})

计数

count = collection.find().count()

print(count)

3

C:\Users\hgvgh\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: count is deprecated. Use Collection.count_documents instead.

"""Entry point for launching an IPython kernel.

统计符合某个条件的数据

count = collection.find({'age': 20}).count()

print(count)

2

C:\Users\hgvgh\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: count is deprecated. Use Collection.count_documents instead.

"""Entry point for launching an IPython kernel.

排序

results = collection.find().sort('name', pymongo.ASCENDING)

print([result['name'] for result in results])

['Jordan', 'Jordan', 'Mike']

这里我们调用 pymongo.ASCENDING 指定升序。如果要降序排列,可以传入 pymongo.DESCENDING。

偏移

在某些情况下,我们可能只需要取某几个元素,这时可以利用 skip 方法偏移几个位置,比如偏移 2,就代表忽略前两个元素,得到第 3 个及以后的元素:

results = collection.find().sort('name', pymongo.ASCENDING).skip(2)

print([result['name'] for result in results])

['Mike']

此外,还可以通过limit方法指定要取的结果个数

results = collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(1)

print([result['name'] for result in results])

['Jordan']

值得注意的是,在数据量非常庞大的时候,比如在查询千万、亿级别的数据库时,最好不要使用大的偏移量,因为这样很可能导致内存溢出。

更新

condition = {'name': 'Mike'}

student = collection.find_one(condition)

student['age'] = 28

result = collection.update_one(condition, {'$set': student})

print(result)

print(result.matched_count, result.modified_count)

1 1

condition = {'age': {'$gt': 20}}

result = collection.update_one(condition, {'$inc': {'age': 1}})

print(result)

print(result.matched_count, result.modified_count)

1 1

这里指定查询条件为年龄大于 20,然后更新条件为 {'$inc': {'age': 1}},表示年龄加 1,执行之后会将第一条符合条件的数据年龄加 1。

如果调用 update_many 方法,则会将所有符合条件的数据都更新,示例如下:

condition = {'age': {'$gt': 20}}

result = collection.update_many(condition, {'$inc': {'age': 1}})

print(result)

print(result.matched_count, result.modified_count)

1 1

删除

result = collection.delete_one({'name': 'Mike'})

print(result.deleted_count)

0

其他操作

另外,PyMongo 还提供了一些组合方法,如 find_one_and_delete、find_one_and_replace 和 find_one_and_update,它们分别用于查找后删除、替换和更新操作,其使用方法与上述方法基本一致。

另外,我们还可以对索引进行操作,相关方法有 create_index、create_indexes 和 drop_index 等。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值