Python與Mongodb交互


MongoDB 是由C++語言編寫的,是一個基於分布式文件存儲的開源數據庫系統


MongoDB 旨在為WEB應用提供可擴展的高性能數據存儲解決方案


MongoDB 將數據存儲為一個文檔,數據結構由鍵值(key=>value)對組成。MongoDB 文檔類似於 JSON 對象。字段值可以包含其他文檔,數組及文檔數組


下載安裝

1 curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz # 下載
2 tar -zxvf mongodb-linux-x86_64-3.0.6.tgz # 解壓
3 mv mongodb-linux-x86_64-3.0.6/ /usr/local/mongodb # 將解壓包拷貝到指定目錄
4 export PATH=<mongodb-install-directory>/bin:$PATH #<mongodb-install-directory> 為Mongo的安裝路徑,如本文的 /usr/local/mongodb 
5 mkdir -p /data/db #創建數據庫目錄(啟動指定--dbpath)

 

配置文件

 1 mongod -f MongoDB.conf 指定配置文件(默認在/etc下尋找)
 2 
 3 基本配置
 4 systemLog:
 5 destination: file
 6 path: /usr/local/var/log/mongodb/mongo.log
 7 logAppend: true
 8 storage:
 9 dbPath: /usr/local/var/mongodb
10 net:
11 bindIp: 127.0.0.1
12 port: 11811

 

配置文件參數信息

 1 #數據庫數據存放目錄
 2 dbpath=/usr/local/mongodb304/data
 3 #數據庫日志存放目錄
 4 logpath=/usr/local/mongodb304/logs/mongodb.log 
 5 #以追加的方式記錄日志
 6 logappend = true
 7 #端口號 默認為27017
 8 port=27017 
 9 #以后台方式運行進程
10 fork=true 
11 #開啟用戶認證
12 auth=true
13 #關閉http接口,默認關閉http端口訪問
14 nohttpinterface=true
15 #mongodb所綁定的ip地址
16 bind_ip = 127.0.0.1 
17 #啟用日志文件,默認啟用
18 journal=true 
19 #這個選項可以過濾掉一些無用的日志信息,若需要調試使用請設置為false
20 quiet=true 
21 
22 
23 其他配置參數含義
24 
25 --quiet    # 安靜輸出
26 --port arg    # 指定服務端口號,默認端口27017
27 --bind_ip arg    # 綁定服務IP,若綁定127.0.0.1,則只能本機訪問,不指定默認本地所有IP
28 --logpath arg    # 指定MongoDB日志文件,注意是指定文件不是目錄
29 --logappend    # 使用追加的方式寫日志
30 --pidfilepath arg    # PID File 的完整路徑,如果沒有設置,則沒有PID文件
31 --keyFile arg    # 集群的私鑰的完整路徑,只對於Replica Set 架構有效
32 --unixSocketPrefix arg    # UNIX域套接字替代目錄,(默認為 /tmp)
33 --fork    # 以守護進程的方式運行MongoDB,創建服務器進程
34 --auth    # 啟用驗證
35 --cpu    # 定期顯示CPU的CPU利用率和iowait
36 --dbpath arg    # 指定數據庫路徑
37 --diaglog arg    # diaglog選項 0=off 1=W 2=R 3=both 7=W+some reads
38 --directoryperdb    # 設置每個數據庫將被保存在一個單獨的目錄
39 --journal    # 啟用日志選項,MongoDB的數據操作將會寫入到journal文件夾的文件里
40 --journalOptions arg    # 啟用日志診斷選項
41 --ipv6    # 啟用IPv6選項
42 --jsonp    # 允許JSONP形式通過HTTP訪問(有安全影響)
43 --maxConns arg    # 最大同時連接數 默認2000
44 --noauth    # 不啟用驗證
45 --nohttpinterface    # 關閉http接口,默認關閉27018端口訪問
46 --noprealloc    # 禁用數據文件預分配(往往影響性能)
47 --noscripting    # 禁用腳本引擎
48 --notablescan    # 不允許表掃描
49 --nounixsocket    # 禁用Unix套接字監聽
50 --nssize arg (=16)    # 設置信數據庫.ns文件大小(MB)
51 --objcheck    # 在收到客戶數據,檢查的有效性,
52 --profile arg    # 檔案參數 0=off 1=slow, 2=all
53 --quota    # 限制每個數據庫的文件數,設置默認為8
54 --quotaFiles arg    # number of files allower per db, requires --quota
55 --rest    # 開啟簡單的rest API
56 --repair    # 修復所有數據庫run repair on all dbs
57 --repairpath arg    # 修復庫生成的文件的目錄,默認為目錄名稱dbpath
58 --slowms arg (=100)    # value of slow for profile and console log
59 --smallfiles    # 使用較小的默認文件
60 --syncdelay arg (=60)    # 數據寫入磁盤的時間秒數(0=never,不推薦)
61 --sysinfo    # 打印一些診斷系統信息
62 --upgrade    # 如果需要升級數據庫
63 
64 
65 主/從參數
66 -------------------------------------------------------------------------
67 --master    # 主庫模式
68 --slave    # 從庫模式
69 --source arg    # 從庫 端口號
70 --only arg    # 指定單一的數據庫復制
71 --slavedelay arg    # 設置從庫同步主庫的延遲時間
72 
73 
74 Replicaton 參數
75 --------------------------------------------------------------------------------
76 --fastsync    # 從一個dbpath里啟用從庫復制服務,該dbpath的數據庫是主庫的快照,可用於快速啟用同步
77 --autoresync    # 如果從庫與主庫同步數據差得多,自動重新同步,
78 --oplogSize arg    # 設置oplog的大小(MB)
View Code

 

啟動mongodb

1 ./mongod --dbpath=/data/db -f MongoDB.conf --rest
2 # 默認端口為:27017
3 # MongoDB 提供了簡單的 HTTP 用戶界面。 如果你想啟用該功能,需要在啟動的時候指定參數 --rest
4 # MongoDB 的 Web 界面訪問端口比服務的端口多1000。如果你的#MongoDB運行端口使用默認的27017,你可以在端口號為28017訪問web用戶界面,即地址為:http://localhost:28017

 

連接mongodb

1 # sudo mongo
2 # sudo mongo --port 11811
3 # sudo mongo -u root -p pwd 127.0.0.1:11811/test

 

創建管理員

 1 > use admin 
 2 switched to db admin
 3 > db
 4 admin
 5 > db.createUser({user:'admin',pwd:'123456',roles:[{role:'userAdminAnyDatabase',db:'admin'}]})
 6 Successfully added user: {
 7     "user" : "admin",
 8     "roles" : [
 9         {
10             "role" : "userAdminAnyDatabase",
11             "db" : "admin"
12         }
13     ]
14 }
15 > exit        

 

創建普通用戶

 1 > use mydb
 2 switched to db mydb
 3 > db.createUser({user:'guest',pwd:'123456',roles:[{role:'readWrite',db:'mydb'}]})
 4 Successfully added user: {
 5     "user" : "guest",
 6     "roles" : [
 7         {
 8             "role" : "readWrite",
 9             "db" : "mydb"
10         }
11     ]
12 }
13 > db.auth('guest','123456')
14 1    

 

刪除用戶

1 > db.dropUser("guest")
2 true

 

查看存在用戶

1 > db.system.users.find()
2 { "_id" : "admin.suoning", "user" : "suoning", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "jykZ+hm5QLhfPDKvcOWyZw==", "storedKey" : "uBr5nVjGLGYq0EdKyosDYOl3HA8=", "serverKey" : "S58tTedpS0QvvxanautLsKXc/OY=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
3 { "_id" : "admin.guest", "user" : "guest", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "+pf1zZC1jaiM+GOMZs5qOg==", "storedKey" : "0ul1QMSdcEwwPVB5cq/GriwarCQ=", "serverKey" : "DLLEWO+NAwUd1nwnmLSp3tFpq/8=" } }, "roles" : [ { "role" : "readWrite", "db" : "mydb" } ] }
4 { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "treTBfONTUztxZLy1AU9XA==", "storedKey" : "0IsEBotj0WzElFbzv3CuNRiVix8=", "serverKey" : "gNDkhP+U0ML4P0TGf0pI+F3w3/8=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }

 

數據庫角色

內建的角色

數據庫用戶角色:read、readWrite;
Read:允許用戶讀取指定數據庫
readWrite:允許用戶讀寫指定數據庫

數據庫管理角色:dbAdmin、dbOwner、userAdmin;
dbAdmin:允許用戶在指定數據庫中執行管理函數,如索引創建、刪除,查

看統計或訪問system.profile
userAdmin:允許用戶向system.users集合寫入,可以找指定數據庫里創建、刪除和管理用戶

集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
clusterAdmin:只在admin數據庫中可用,賦予用戶所有分片和復制集相關函數的管理權限 

備份恢復角色:backup、restore;

所有數據庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
readAnyDatabase:只在admin數據庫中可用,賦予用戶所有數據庫的讀權限
readWriteAnyDatabase:只在admin數據庫中可用,賦予用戶所有數據庫的讀寫權限
userAdminAnyDatabase:只在admin數據庫中可用,賦予用戶所有數據庫的userAdmin權限
dbAdminAnyDatabase:只在admin數據庫中可用,賦予用戶所有數據庫的dbAdmin權限。

超級用戶角色:root // 這里還有幾個角色間接或直接提供了系統超級用戶的訪問(dbOwner 、userAdmin、userAdminAnyDatabase)

內部角色:__system


創建超級管理員需要未開啟權限模式的情況下執行;
如果 MongoDB 開啟了權限模式,並且某一個數據庫沒有任何用戶時,在不驗證權限的情況下,可以創建一個用戶,當繼續創建第二個用戶時,會返回錯誤,若想繼續創建用戶則必須登錄;
用戶只能在用戶所在數據庫登錄,管理員需要通過admin認證后才能管理其他數據庫
View Code

 

數據類型

數據類型    描述
String    字符串。存儲數據常用的數據類型。在 MongoDB 中,UTF-8 編碼的字符串才是合法的。
Integer    整型數值。用於存儲數值。根據你所采用的服務器,可分為 32 位或 64 位。
Boolean    布爾值。用於存儲布爾值(真/假)。
Double    雙精度浮點值。用於存儲浮點值。
Min/Max keys    將一個值與 BSON(二進制的 JSON)元素的最低值和最高值相對比。
Arrays    用於將數組或列表或多個值存儲為一個鍵。
Timestamp    時間戳。記錄文檔修改或添加的具體時間。
Object    用於內嵌文檔。
Null    用於創建空值。
Symbol    符號。該數據類型基本上等同於字符串類型,但不同的是,它一般用於采用特殊符號類型的語言。
Date    日期時間。用 UNIX 時間格式來存儲當前日期或時間。你可以指定自己的日期時間:創建 Date 對象,傳入年月日信息。
Object ID    對象 ID。用於創建文檔的 ID。
Binary Data    二進制數據。用於存儲二進制數據。
Code    代碼類型。用於在文檔中存儲 JavaScript 代碼。
Regular expression    正則表達式類型。用於存儲正則表達式。
View Code

 

Python操作Mongodb模塊

1 pip install pymongo 
2 or 
3 easy_install install pymongo

 

操作方式

連接Mongodb

import pymongo

# 建立MongoDB數據庫連接
# connection = pymongo.Connection('192.168.198.128', 27017)

# 如果設置了權限,注意xxx用戶權限要可以cover到后面使用到的數據庫
# client = pymongo.MongoClient('192.168.198.128', 27017, username='guest', password='123456')
client = pymongo.MongoClient('192.168.198.128',27017)

# 連接所需數據庫,test為數據庫名
db=client.test
# db_name = 'test'
# db = client[db_name]

# 連接所用集合,也就是我們通常所說的表,test為表名
# db和collection都是延時創建的,在添加Document時才真正創建
collection=db.test

 

添加數據

first_name = ["","","","",""]
second_name = ["","","","",""]
third_name = ["","","","",""]
data = [
    {"_id":int("1000"+str(i)),
     "name":random.choice(first_name)+
            random.choice(second_name)+
            random.choice(third_name),
     "age":random.randint(16,60),
     "high":random.randint(170,190),
     "list":list(random.randint(1,200) for i in range(10))
    } for i in range(5)
]
try:
    for record in data:
        collection.save(record)
except pymongo.errors.DuplicateKeyError:
    print('record exists')
except Exception as e:
    print(e)


刪除數據

collection.delete_many({'age':{'$gt':20,'$lt':30}})   #刪除所有滿足條件的文檔,刪除_id大於6,小於100
collection.delete_one({'age':20})                     #刪除一條滿足條件的文檔,刪除_id=6
#collection_set01.delete_many({})                     #刪除整個集合

 

更新數據

collection.replace_one({'_id': 10000}, {'name': '王寶寶'})                         #replace_one用指定的key-value替代原來所有的key-value
collection.update_one({"_id": {'$lt': 10008}}, {'$set': {"age": "19"}})           #update_one更新已經對應的key-value,其它不變
collection.update_many({'_id': {'$gt': 10007}}, {'$set': {'age': '50'}})          #同上,能夠update所有符合匹配條件的文檔

 

查詢數據

print('\n------------身高小於180:')
print(type(collection.find({'high':{'$lt':180}})))
for row in collection.find({'high':{'$lt':180}}):
    print(row)
print(type(collection.find_one({'high':{'$lt':180}})))
print('use find_one:',collection.find_one({'high':{'$lt':180}})['high'])
print('use find_one:',collection.find_one({'high':{'$lt':180}}))

print('\n------------查詢特定鍵')
print('------------查詢身高大於170,並只列出_id,high和age字段(使用列表形式_id默認打印出來,可以使用{}忽視_id):')
for row in collection.find({'high':{'$gt':170}},projection=['high','age']):
    print(row)

print('\n------------skip參數用法')
for row in collection.find({'high':{'$gt':170}},['high','age'],skip=1):
    print(row)
for row in collection.find({'high':{'$gt':170}},['high','age']).skip(1):
    print(row)

print('\n------------limit參數用法')
for row in collection.find({'high':{'$gt':170}},['high','age'],limit=1):
    print(row)

print('\n------------用{}描述特定鍵')
for row in collection.find({'high':{'$gt':170}},{'high':1,'age':1,'_id':False}):
    print(row)

print('\n------------多條件查詢')
print(collection.find_one({'high':{'$gt':10},'age':{'$lt':26,'$gt':10}}))


# for u in db.users.find({"age":{"$nin":(23, 26, 32)}}):
# print u
# select * from users where age not in (23, 26, 32)

print('\n------------count')
print(collection.find({"age":{"$gt":20}}).count())

print('\n------------條件或')
print('大於等於29或者小於23')
for row in collection.find({"$or":[{"age":{"$lte":23}}, {"age":{"$gte":29}}]}):
    print(row)

print('\n------------exists')
for row in collection.find({'age':{'$exists':True}}):
    print('age exists',row) # select * from 集合名 where exists 鍵1
for row in collection.find({'age':{'$exists':False}}):
    print('age not exists',row)

print('\n------------正則表達式查詢')
print('method 1')
for row in collection.find({'name':{'$regex':r'.*暖.*'}}):
    print(row)
print('method 2')
import re
Regex = re.compile(r'.*愛.*',re.IGNORECASE)
for row in collection.find({'name':Regex}):
    print(row)

print('\n------------使用sort排序(文檔中沒有排序的字段也會打印出來,表示最小)')
print('------------age 升序')
for row in collection.find().sort([["age",pymongo.ASCENDING]]):
    print(row)
print('------------age 降序')
for row in collection.find().sort([("age",-1)]):
    print(row)
print('------------age升序,high升序')
for row in collection.find().sort((("age",pymongo.ASCENDING),("high",pymongo.ASCENDING))):
    print(row)
print('------------age升序,high降序')
for row in collection.find(sort=[("age",pymongo.ASCENDING),("high",pymongo.ASCENDING)]):
    print(row)

print('\n------------$all')
for row in collection.find({'list':{'$all':[77,117,165,37,57,49,178,90,3,166]}}):
    print(row)

print('\n------------$in')
for row in collection.find({'list':{'$in':[2,3,4]}}):
    print(row)

print('\n------------size=10')
for row in collection.find({'list':{'$size':10}}):
    print(row)
    
    
# print('-------------------$unset')
# print('$unset和$set相反表示移除文檔屬性')
# print('---before')
# for row in collection.find({'name': "張程芬"}):
#     print(row)
# collection.update({'name':'張程芬'},{'$unset':{'age':1}})
# print('---after')
# for row in collection.find({'name':'張程芬'}):
#     print(row)

 

 完整代碼文件

__author__ = 'Cq'

import pymongo
import random



def add_data(collection):
    first_name = ["","","","",""]
    second_name = ["","","","",""]
    third_name = ["","","","",""]
    data = [
        {"_id":int("1000"+str(i)),
         "name":random.choice(first_name)+
                random.choice(second_name)+
                random.choice(third_name),
         "age":random.randint(16,60),
         "high":random.randint(170,190),
         "list":list(random.randint(1,200) for i in range(10))
        } for i in range(5)
    ]
    try:
        for record in data:
            collection.save(record)
    except pymongo.errors.DuplicateKeyError:
        print('record exists')
    except Exception as e:
        print(e)


def delete_data(collection):
    remove_before = collection.find()
    print('---------------delete before--------------------')
    for obj in remove_before:
        print(obj)

    collection.delete_many({'age':{'$gt':20,'$lt':30}})   #刪除所有滿足條件的文檔,刪除_id大於6,小於100
    collection.delete_one({'age':20})                     #刪除一條滿足條件的文檔,刪除_id=6
    #collection_set01.delete_many({})                     #刪除整個集合
    remove_after = collection.find()

    print('---------------delete after--------------------')
    for obj in remove_after:
        print(obj)


def update_data(collection):
    collection.replace_one({'_id': 10000}, {'name': '王寶寶'})                         #replace_one用指定的key-value替代原來所有的key-value
    collection.update_one({"_id": {'$lt': 10008}}, {'$set': {"age": "19"}})           #update_one更新已經對應的key-value,其它不變
    collection.update_many({'_id': {'$gt': 10007}}, {'$set': {'age': '50'}})          #同上,能夠update所有符合匹配條件的文檔



def select_data(collection):

    print('\n------------身高小於180:')
    print(type(collection.find({'high':{'$lt':180}})))
    for row in collection.find({'high':{'$lt':180}}):
        print(row)
    print(type(collection.find_one({'high':{'$lt':180}})))
    print('use find_one:',collection.find_one({'high':{'$lt':180}})['high'])
    print('use find_one:',collection.find_one({'high':{'$lt':180}}))

    print('\n------------查詢特定鍵')
    print('------------查詢身高大於170,並只列出_id,high和age字段(使用列表形式_id默認打印出來,可以使用{}忽視_id):')
    for row in collection.find({'high':{'$gt':170}},projection=['high','age']):
        print(row)

    print('\n------------skip參數用法')
    for row in collection.find({'high':{'$gt':170}},['high','age'],skip=1):
        print(row)
    for row in collection.find({'high':{'$gt':170}},['high','age']).skip(1):
        print(row)

    print('\n------------limit參數用法')
    for row in collection.find({'high':{'$gt':170}},['high','age'],limit=1):
        print(row)

    print('\n------------用{}描述特定鍵')
    for row in collection.find({'high':{'$gt':170}},{'high':1,'age':1,'_id':False}):
        print(row)

    print('\n------------多條件查詢')
    print(collection.find_one({'high':{'$gt':10},'age':{'$lt':26,'$gt':10}}))


    # for u in db.users.find({"age":{"$nin":(23, 26, 32)}}):
    # print u
    # select * from users where age not in (23, 26, 32)

    print('\n------------count')
    print(collection.find({"age":{"$gt":20}}).count())

    print('\n------------條件或')
    print('大於等於29或者小於23')
    for row in collection.find({"$or":[{"age":{"$lte":23}}, {"age":{"$gte":29}}]}):
        print(row)

    print('\n------------exists')
    for row in collection.find({'age':{'$exists':True}}):
        print('age exists',row) # select * from 集合名 where exists 鍵1
    for row in collection.find({'age':{'$exists':False}}):
        print('age not exists',row)

    print('\n------------正則表達式查詢')
    print('method 1')
    for row in collection.find({'name':{'$regex':r'.*暖.*'}}):
        print(row)
    print('method 2')
    import re
    Regex = re.compile(r'.*愛.*',re.IGNORECASE)
    for row in collection.find({'name':Regex}):
        print(row)

    print('\n------------使用sort排序(文檔中沒有排序的字段也會打印出來,表示最小)')
    print('------------age 升序')
    for row in collection.find().sort([["age",pymongo.ASCENDING]]):
        print(row)
    print('------------age 降序')
    for row in collection.find().sort([("age",-1)]):
        print(row)
    print('------------age升序,high升序')
    for row in collection.find().sort((("age",pymongo.ASCENDING),("high",pymongo.ASCENDING))):
        print(row)
    print('------------age升序,high降序')
    for row in collection.find(sort=[("age",pymongo.ASCENDING),("high",pymongo.ASCENDING)]):
        print(row)

    print('\n------------$all')
    for row in collection.find({'list':{'$all':[77,117,165,37,57,49,178,90,3,166]}}):
        print(row)

    print('\n------------$in')
    for row in collection.find({'list':{'$in':[2,3,4]}}):
        print(row)

    print('\n------------size=10')
    for row in collection.find({'list':{'$size':10}}):
        print(row)


    # print('-------------------$unset')
    # print('$unset和$set相反表示移除文檔屬性')
    # print('---before')
    # for row in collection.find({'name': "張程芬"}):
    #     print(row)
    # collection.update({'name':'張程芬'},{'$unset':{'age':1}})
    # print('---after')
    # for row in collection.find({'name':'張程芬'}):
    #     print(row)



def main():
    client = pymongo.MongoClient('192.168.198.128', 27017, username='guest', password='123456')

    db = client.test

    collection = db.test

    add_data(collection)

    update_data(collection)

    select_data(collection)

    delete_data(collection)


if "__main__" == __name__:
    main()
View Code

輸出結果

 1 ------------身高小於180:
 2 <class 'pymongo.cursor.Cursor'>
 3 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
 4 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
 5 <class 'dict'>
 6 use find_one: 172
 7 use find_one: {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
 8 
 9 ------------查詢特定鍵
10 ------------查詢身高大於170,並只列出_id,high和age字段(使用列表形式_id默認打印出來,可以使用{}忽視_id):
11 {'_id': 10001, 'age': 21, 'high': 186}
12 {'_id': 10002, 'age': 24, 'high': 172}
13 {'_id': 10004, 'age': 41, 'high': 182}
14 
15 ------------skip參數用法
16 {'_id': 10002, 'age': 24, 'high': 172}
17 {'_id': 10004, 'age': 41, 'high': 182}
18 {'_id': 10002, 'age': 24, 'high': 172}
19 {'_id': 10004, 'age': 41, 'high': 182}
20 
21 ------------limit參數用法
22 {'_id': 10001, 'age': 21, 'high': 186}
23 
24 ------------用{}描述特定鍵
25 {'age': 21, 'high': 186}
26 {'age': 24, 'high': 172}
27 {'age': 41, 'high': 182}
28 
29 ------------多條件查詢
30 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
31 
32 ------------count
33 4
34 
35 ------------條件或
36 大於等於29或者小於23
37 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
38 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
39 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
40 
41 ------------exists
42 age exists {'_id': 10000, 'name': '王寶寶', 'age': '19'}
43 age exists {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
44 age exists {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
45 age exists {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
46 age exists {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
47 
48 ------------正則表達式查詢
49 method 1
50 method 2
51 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
52 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
53 
54 ------------使用sort排序(文檔中沒有排序的字段也會打印出來,表示最小)
55 ------------age 升序
56 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
57 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
58 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
59 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
60 {'_id': 10000, 'name': '王寶寶', 'age': '19'}
61 ------------age 降序
62 {'_id': 10000, 'name': '王寶寶', 'age': '19'}
63 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
64 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
65 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
66 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
67 ------------age升序,high升序
68 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
69 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
70 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
71 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
72 {'_id': 10000, 'name': '王寶寶', 'age': '19'}
73 ------------age升序,high降序
74 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
75 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
76 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
77 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
78 {'_id': 10000, 'name': '王寶寶', 'age': '19'}
79 
80 ------------$all
81 
82 ------------$in
83 
84 ------------size=10
85 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
86 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
87 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
88 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
89 ---------------delete before--------------------
90 {'_id': 10000, 'name': '王寶寶', 'age': '19'}
91 {'_id': 10001, 'name': '王鑫風', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
92 {'_id': 10002, 'name': '趙愛風', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
93 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
94 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
95 ---------------delete after--------------------
96 {'_id': 10000, 'name': '王寶寶', 'age': '19'}
97 {'_id': 10003, 'name': '李愛風', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
98 {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
View Code

 參考博客https://www.cnblogs.com/diaosir/p/6507178.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM