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

本文介绍了Pymongo中常见的高级操作技巧,包括利用$elemMatch查询数组元素、使用$unset删除字段信息、通过upsert参数实现数据更新或插入、采用$regex进行正则表达式文本查询以及设置projection参数来过滤指定字段。

总结一下最近包括之前遇到的一些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里边都包含这个参数,现在贴一下源码。

Paste_Image.png

Paste_Image.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值