1 find()多用$in 少用$or
2 搜索一个嵌套有序的列表
from bson.son import SON # 排序
cursor = db.inventory.find(
{"size": SON([("h", 14), ("w", 21), ("com", "cm")])})
3 find array
4 依据列表中的元素筛选
from db.mongo.connectionSyn import Connection
db = Connection()
db.test.insert_many([
{"item": "journal",
"qty": 25,
"tags": ["blank", "red"],
"dim_cm": [14, 21]},
{"item": "notebook",
"qty": 50,
"tags": ["red", "blank"],
"dim_cm": [14, 21]},
{"item": "paper",
"qty": 100,
"tags": ["red", "blank", "plain"],
"dim_cm": [14, 21]},
{"item": "planner",
"qty": 75,
"tags": ["blank", "red"],
"dim_cm": [22.85, 30]},
{"item": "postcard",
"qty": 45,
"tags": ["blue"],
"dim_cm": [10, 15.25]}])
cursor = db.test.find({"dim_cm": {"$gt": 15, "$lt": 20}})
for i in cursor:
print(i)
print('$elemMatch')
》》》》》》》》result 存在满足的就返回
{'_id': ObjectId('5d779cf86215315e74371e98'), 'item': 'journal', 'qty': 25, 'tags': ['blank', 'red'], 'dim_cm': [14, 21]}
{'_id': ObjectId('5d779cf86215315e74371e99'), 'item': 'notebook', 'qty': 50, 'tags': ['red', 'blank'], 'dim_cm': [14, 21]}
{'_id': ObjectId('5d779cf86215315e74371e9a'), 'item': 'paper', 'qty': 100, 'tags': ['red', 'blank', 'plain'], 'dim_cm': [14, 21]}
{'_id': ObjectId('5d779cf86215315e74371e9c'), 'item': 'postcard', 'qty': 45, 'tags': ['blue'], 'dim_cm': [10, 15.25]}
cursor = db.test.find(
{"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
for i in cursor:
print(i)
》》》》》》》》result 全都返祖才返回
{'_id': ObjectId('5d779cf86215315e74371e9b'), 'item': 'planner', 'qty': 75, 'tags': ['blank', 'red'], 'dim_cm': [22.85, 30]}