英文:
MongoDB query does not update document record
问题
I'm using pymongo
version 4.3.3 and motor
version 3.1.2
This is my code:
async def add_reputation_to_db(
self,
guild_id: hikari.Snowflake,
user_recieve_id: hikari.Snowflake,
) -> None:
await self._guild_collection.update_one({'_id': guild_id}, {'$inc': {f'{user_recieve_id}.reputation': 1}})
I have no errors with it, but the problem is that the database does not update any data if I use a point to jump to a certain key in the dictionary, in my case it is {user_recieve_id}.reputation
.
The hierarchy of my document looks like this:
{
'_id': guild_id,
'user_id': {
'reputation': 123
}
}
But user_id
must be the user identifier as a number.
I looked for solutions on the Internet and ChatGPT, but it did not give me any results.
英文:
Im using pymongo
version 4.3.3 and motor
version 3.1.2
This is my code:
async def add_reputation_to_db(
self,
guild_id: hikari.Snowflake,
user_recieve_id: hikari.Snowflake,
) -> None:
await self._guild_collection.update_one({'_id': guild_id}, {'$inc': {f'{user_recieve_id}.reputation': 1}})
I have no errors with it, but the problem is that database does not update any data if I use a point to jump to a certain key in the dictionary, in my case it is f'{user_recieve_id}.reputation'
.
The hierarchy of my document looks like this:
{
'_id': guild_id,
'user_id': {
'reputation': 123
}
}
But user_id
must be the user identifier as number.
I looked for solutions on the Internet and ChatGPT, but it did not give me any results.
答案1
得分: 1
这段代码片段似乎有效。请注意,如果没有匹配的 _id
,则不会设置任何内容。
from pymongo import MongoClient
db = MongoClient()['mydatabase']
guild_id = 1
user_recieve_id = 'user1'
coll.insert_one({"_id": guild_id})
coll.update_one({'_id': guild_id}, {'$inc': {f'{user_recieve_id}.reputation': 1}})
print(coll.find_one())
coll.update_one({'_id': guild_id}, {'$inc': {f'{user_recieve_id}.reputation': 1}})
print(coll.find_one())
输出结果:
{'_id': 1, 'user1': {'reputation': 1}}
{'_id': 1, 'user1': {'reputation': 2}}
英文:
This code snippet seems to work. Note that if you don't have a matching _id
nothing will be set.
from pymongo import MongoClient
db = MongoClient()['mydatabase']
guild_id = 1
user_recieve_id = 'user1'
coll.insert_one({"_id": guild_id})
coll.update_one({'_id': guild_id}, {'$inc': {f'{user_recieve_id}.reputation': 1}})
print(coll.find_one())
coll.update_one({'_id': guild_id}, {'$inc': {f'{user_recieve_id}.reputation': 1}})
print(coll.find_one())
prints:
{'_id': 1, 'user1': {'reputation': 1}}
{'_id': 1, 'user1': {'reputation': 2}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论