MongoDB查询未更新文档记录。

huangapple go评论77阅读模式
英文:

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}}

huangapple
  • 本文由 发表于 2023年6月26日 16:18:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定