天天看點

Pymongo一些常見需求(陸續補充)需求3: 更新一條資料,如果資料不存在則插入此資料

總結一下最近包括之前遇到的一些pymongo操作的問題。

#需求1: 搜尋文檔數組裡邊是否存在某元素

資料:

data1 = {
    '_id': xxxxxxxxxxxxxx,
    'dataList': [
    'apple',  'grape', 'banana'
]
}
data2 = {
    '_id': xxxxxxxxxxxxxx,
    'dataList': [
    'watermelon',  'mango'
]
}           

關鍵字: $elemMatch

查詢方法:

db.find({'$elemMatch': {'dataList': 'mango'}})
           

這樣就可以找到水果資料清單裡邊mango所在的document了。

#需求2: 删除文檔的某個字段的某些資訊

資料:

data = {
    '_id': "xxxxxxxx"
    'userInfo': {"name": "Woody", "age": 24, "weight": 10}
}           

現在我想删除userInfo裡邊的weight資訊。

關鍵字: $unset

db.update({'_id': 'xxxxxxxx'}, {'$unset': {'userInfo.weight': 10}})           

這樣就可以删除掉userInfo裡邊的weight資訊了,補充一點,userInfo和weight之間的連接配接用“.”來表示。

需求3: 更新一條資料,如果資料不存在則插入此資料

關鍵字: upsert參數置為True

在update, update_one, update_many裡邊都包含這個參數,現在貼一下源碼。

Pymongo一些常見需求(陸續補充)需求3: 更新一條資料,如果資料不存在則插入此資料
Pymongo一些常見需求(陸續補充)需求3: 更新一條資料,如果資料不存在則插入此資料

可以看到源碼裡的解釋是,如果upsert參數為True,則會在沒有找到文檔的時候插入這條資料(此時是可以代替insert操作的)。

#需求4: 使用正規表達式查詢文檔裡的文本

關鍵字: $regex

data = {
    '_id': "xxxxxxxx",
    'content': 'hello, this is a url for baidu, it is https://www.baidu.com'
}
db.find({"content": {"$regex": r"https://[\w\.]+"}})
           

#需求5: 過濾不需要的字段

關鍵字: projection參數

例如我想過濾掉id,我隻要content和name字段

data = {
    '_id': "xxxxxxxx",
    'content': 'hello, this is a url for baidu, it is https://www.baidu.com',
    'name': '百度首頁'
}
db.find({"content": {"$regex": r"https://[\w\.]+"}}, projection={'_id':0, 'name':1, 'content':1})