Pymongo一些常见需求(陆续补充)

时间:2023-03-10 06:04:24
Pymongo一些常见需求(陆续补充)

总结一下最近包括之前遇到的一些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一些常见需求(陆续补充)

Pymongo一些常见需求(陆续补充)

可以看到源码里的解释是,如果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})