Pymongo操作未返回任何结果
我有此代码:
def add_new_category(group_id: str, name: str) -> tuple:
"""
Used to add a new transaction category
:param group_id: str
:param name: str
:return: tuple of bool and result
"""
try:
current_app.logger.info("add_new_category function called ...")
if len(list(db.groups_categories.find())) == 0:
data = {
"group_id": group_id,
"categories": [{
"cat_id": ObjectId(),
"name": name,
"created_at": now
}]
}
result = db.groups_categories.insert_one(data).inserted_id
_d = db.groups_categories.find().sort('group_id', pymongo.ASCENDING).limit(1)
else:
result = db.groups_categories.update_one({"group_id": ObjectId(group_id)}, {"$push": {"categories": {
"cat_id": ObjectId(),
"name": name,
"created_at": now
}}})
_d = db.groups_categories.find().sort('group_id', pymongo.ASCENDING).limit(1)
except Exception as e:
current_app.logger.error(f"add_new_category error: {e}")
函数最初应添加记录和后续操作应将对象附加到类别阵列。第一部分有效,但第二部分没有错误,但没有附加对象。
我已经使用了24小时以上,我似乎找不到为什么第二个操作(update_one)不起作用。任何指针都会有所帮助。
请注意,我正在从我的Localhost的Atlas实例上添加此数据,并使用Pymongo库为MongoDB添加。
来自Update_One操作的日志:
In second else ...
[2022-06-15 09:11:49 +0100] [48333] [INFO] db_init Function called ...
M: []
[2022-06-15 09:11:51 +0100] [48333] [INFO] db_init Function called ...
[2022-06-15 09:11:54 +0100] [48333] [INFO] db_init Function called ...
REMADD:127.0.0.1 - USER:- RDATE:[15/Jun/2022:09:11:57 +0100] METHOD:POST URL:/api/v1.0/transactions/categories PROTO:HTTP/1.1 STATUS:200 UAGENT:PostmanRuntime/7.26.8 PID:<48333>
整体工作流程:
检查集合是否为空,如果可以
- 将记录插入并返回并返回,否则
- 将新对象记录附加到类别 array rane
结果(s):
插入操作有效,但推动操作却没有。没有显示错误,但是类别阵列并未按预期更新。
I have this code:
def add_new_category(group_id: str, name: str) -> tuple:
"""
Used to add a new transaction category
:param group_id: str
:param name: str
:return: tuple of bool and result
"""
try:
current_app.logger.info("add_new_category function called ...")
if len(list(db.groups_categories.find())) == 0:
data = {
"group_id": group_id,
"categories": [{
"cat_id": ObjectId(),
"name": name,
"created_at": now
}]
}
result = db.groups_categories.insert_one(data).inserted_id
_d = db.groups_categories.find().sort('group_id', pymongo.ASCENDING).limit(1)
else:
result = db.groups_categories.update_one({"group_id": ObjectId(group_id)}, {"$push": {"categories": {
"cat_id": ObjectId(),
"name": name,
"created_at": now
}}})
_d = db.groups_categories.find().sort('group_id', pymongo.ASCENDING).limit(1)
except Exception as e:
current_app.logger.error(f"add_new_category error: {e}")
The function should initially add a record and subsequent operations should append an object to to categories array. The first part works but the second part gives no error but no object is appended.
I have been on this for over 24hrs and I can't seem to find why the second operation (update_one) is not working. Any pointers would really help.
Please note I am adding this data on an atlas instance from my localhost and using the pymongo library for mongodb.
Logs from the update_one operation:
In second else ...
[2022-06-15 09:11:49 +0100] [48333] [INFO] db_init Function called ...
M: []
[2022-06-15 09:11:51 +0100] [48333] [INFO] db_init Function called ...
[2022-06-15 09:11:54 +0100] [48333] [INFO] db_init Function called ...
REMADD:127.0.0.1 - USER:- RDATE:[15/Jun/2022:09:11:57 +0100] METHOD:POST URL:/api/v1.0/transactions/categories PROTO:HTTP/1.1 STATUS:200 UAGENT:PostmanRuntime/7.26.8 PID:<48333>
Overall workflow:
Check to see that the collection is empty and if so
- Insert a record into it and return, else
- append an new object record into the categories array
Result(s):
The insertion operation works but push operation doesn't. No errors shown but the categories array isn't updated as expected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设连续调用中的
group_id
与您需要始终如一地使用它相同。您可以将其插入以下字符串中,
然后按从字符串生成的objectid进行过滤以进行更新:
mongo比较类型,字符串永远不等于对象。没有匹配过滤器参数的文档,因此更新会影响0个文档。
在两个查询中使用字符串或obkectids。
我对OP的所有评论仍然有效。代码中存在许多缺陷,因此仅解决此问题将导致特定条件下的意外结果。
Assuming
group_id
in consecutive calls is the same you need to use it consistently.You insert it as plain string in:
And filter by an objectId generated from the string for update:
Mongo compare types, a string never equal to an object. There are no documents matching the filter argument, so update affects 0 documents.
Either use strings or ObkectIds in both queries.
All my comments to the OP are still valid. There are number of flaws in the code, so fixing this issue alone will result with unexpected results in specific conditions.