Pymongo skill

记录PyMongo的常用技巧

一次性更新多个字段

1
2
3
4
5
6
7
way_bill = self.db.Waybill.update_one({"_id": waybill_id}, {
'$set':{
"user": self.user["_id"],
"status": 1
}
})

mongodb小坑

pymong每次查询之后 只能进行一次迭代 建议将数据转化成list

1
all_waybills = list(self.db.Waybill.find({"status": 0}))
有多个or条件时,不同的字段的or条件要分开写,否则查询没有效果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
orders = list(self.db.Order.find({
"$and":[
{"content": {'$elemMatch': {'suppliers': self.user['_id']}}},
{"$or": [
{"status": 1},
{"status": 2},
]},
{"$or": [
{"type": 2},
{"type": 3},
{"type": 4},
]}
]
}))

多条件筛选进行更新

尽量不使用update_many,使用update,也可达到一次更新多个的效果。

1
2
_filter = {"order": _id, "status": 0}                      
self.db.Waybill.update(_filter, {"$set": {"status": status}})

或者 优先考虑使用这种方式

1
2
_filter = [{"order": _id}, {"status": 4}]
self.db.Waybill.update_many({"$and": _filter}, {"$set": {"status": 5}})

模糊匹配

目标对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
"_id": ObjectId("598bcb0fc3344d4511952921"),
"arrivaltime": 1502592911,
"contact": "鲁肃",a
"contact_phone": "13589896969",
"content": [
{
"type": 2,
"name": "右江SPC16.6",
"status": 0,
"count": 0,
"intorduce": "右江SPC16.6 最好的SPC16.6水泥",
"price": 230,
"suppliers": ObjectId("5979aaea132855361289842b"),
"_id": ObjectId("598bcc03c3344d4511952922"),
"account": "旺鑫户头",
"origin_address": ObjectId("597bfb58c3344d6d584f595b"),
"is_open": 1,
"images": "http://opkf7ecvv.bkt.clouddn.com/FnK5A9P5h3F9CwlBV8gDWbk9at_x"
}
],
"count": 2,
"createtime": 1502333711,
"destination": "广西壮族自治区-百色市-西林县",
"destination_detail": "八大河乡",
"destination_location": "24.657053,104.498372",
"freight": ObjectId("597dd0bbc3344d56153e6065"),
"is_pay": 0,
"load": 50,
"origin": "广西壮族自治区-百色市-田阳县",
"origin_detail": "华润水泥田阳有限公司",
"origin_location": "23.757743,106.769572",
"price": 23000,
"status": 7,
"type": 2,
"user": ObjectId("5979b4a9132855361289842d")
}

匹配语法

1
2
query = {"$and": [{'content': {'$elemMatch': {'suppliers': self.user['_id']}}}]}
orders = list(self.db.Order.find(query))

Python数据处理

1
浮点数保留两位小数:float("%.2f" % unpdate_content["price"])

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!