mongodb多条件筛选

1,253 阅读1分钟

1.参考链接

MongoDB逻辑操作符or,or, and,not,not,nor

Python操作MongoDB看这一篇就够了

2. 链接数据库

import pymongo
import pandas as pd
from icecream import ic
client = pymongo.MongoClient('mongodb://jevy:112244@localhost:27017/')
db = client['US_AMZ']
collection =  db['slope_2022_market']  # 数据库的名称

image.png

image.png

2.1 使用 in 的方法

image.png

2.2 隐式AND操作

直接使用大的字典格式:是and的关系

con1={'last_week_rank': {'$gte': 5000, '$lt': 8000},
                            'this_click_focus': {'$gte': 10, '$lt': 20},
                            'this_con_focus': {'$gte': 10, '$lt': 20},
                            'two_month_slope': {'$lte': 0}}
                            

collect.count_documents(con1)

image.png

res=collect.find(con1)
res=collect.find(con1)
df=pd.DataFrame(res)
df

image.png

2.2 显示 AND

在条件1的基础上 增加新的筛选条件,使用and连接 '$in' 后面的列表 表示筛选的时候 结果跟列表的元素一样

con2={'$and':[{'searchTerm':{'$in': ['retro toys' ,'st patricks day gnomes']}  },con1]}
collect.count_documents(con2)

image.png 结果只有两个。

3使用排除的标签,

3.1 使用正则表达式

## { $nor: [ { <expression1> }, { <expression2> }, ...  { <expressionN> } ] }
# 链接 :https://blog.csdn.net/yaomingyang/article/details/75103480
## $not 不支持 正则表达式   db.inventory.find( { item: { $not: /^p.*/ } } )
# {$regex: 'ttt'}通常相当于/ttt/在 mongodb 中,因此您的查询将变为db.test.find({c: {$not: /ttt/}}
c1={ 'searchTerm' : { '$not' : re.compile('retro toys')  }  }
con3={'$and':[c1  ,con1]}
res=collect.find(con3)
df=pd.DataFrame(res)
df

image.png 排除掉一个。

3.2 使用正则表达式 包含某个关键词

c1={ 'searchTerm' :{'$regex': 'retro toys.*'}   }
con4={'$and':[c1  ,con1]}
res=collect.find(con4)
df=pd.DataFrame(res)
df

image.png