天天看點

mongodb $inc 加小數_使用Python操作mongodb資料庫

mongodb $inc 加小數_使用Python操作mongodb資料庫

原文位址:http://www.mapboxx.cn/article/mongodb/

安裝MongoDB

安裝教程詳見:https://www.runoob.com/mongodb/mongodb-window-install.html

啟動mongodb服務指令:

mongod --dbpath C:softwaremongodbdatadb
           

其中,

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)
<pymongo.results.InsertOneResult object at 0x00000177658B0408>
           

同時插入多條資料

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)
<pymongo.results.InsertManyResult object at 0x000001776586FE48>
           

查詢資料

result = collection.find_one({'name':'Mike'})
print(type(result))
print(result)
<class 'dict'>
{'_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'}
           
mongodb $inc 加小數_使用Python操作mongodb資料庫

正則比對

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

計數

count = collection.find().count()
print(count)
3


C:UsershgvghAnaconda3libsite-packagesipykernel_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:UsershgvghAnaconda3libsite-packagesipykernel_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)
<pymongo.results.UpdateResult object at 0x0000017765A53988>
1 1
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
<pymongo.results.UpdateResult object at 0x0000017765ABAE08>
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)
<pymongo.results.UpdateResult object at 0x0000017765ABA888>
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 等。

關于 PyMongo 的詳細用法,可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/collection.html。

另外,還有對資料庫和集合本身等的一些操作,這裡不再一一講解,可以參見官方文檔:http://api.mongodb.com/python/current/api/pymongo/。