[英]How to set a collection name in MongoDB
I encountered such a problem, I do not know how to set the name of this collection through the code when creating a collection, that is, I write:遇到这样一个问题,不知道怎么在创建集合的时候通过代码设置这个集合的名字,也就是我这样写:
cluster = MongoClient("link")
db = cluster.BananiData
collection = db.ctx.guild.id
but the name is set as ctx.guild.id, I need to insert the server ID in the name, how can this be implemented?但是名称设置为ctx.guild.id,我需要在名称中插入服务器ID,如何实现?
PS: I use python PS:我用的是 python
code:代码:
cluster = MongoClient("mongodb+srv://Bananchik:hdkkIFkk6VKywSDH@cluster0.olcto.mongodb.net/<BananiData>?retryWrites=true&w=majority")
db = cluster.BananiData
collection = db.ctx.guild.id
#collection = cluster.BananiData.LevelSystem
class DataBases(commands.Cog):
""" ФСБ? """
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.check(permissions.is_owner)
async def test_db(self, ctx):
await ctx.send(collection)
await ctx.send("DB id created")
for member in ctx.guild.members:
print(member)
post = {
"_id": member.id,
"xp": 0,
"lvl": 1,
"message_count": 0
}
if collection.count_documents({"_id": member.id}) == 0:
collection.insert_one(post)
print(f"Пользователь **{member.name}** добавлен в базу данных")
It is a good practice to enclose the name you want to assign to a collection inside a square bracket if you are using python.如果您使用的是 python,最好将要分配给集合的名称括在方括号内。
Example:例子:
If you want to create a collection by the name "SampleCollection", you could use the below command, even though .
如果你想创建一个名为“SampleCollection”的集合,你可以使用下面的命令,即使.
operator works.操作员工作。
collection = db["SampleCollection"]
Therefore,所以,
You should change the collection initialization code like the following:您应该更改集合初始化代码,如下所示:
collection = db[ctx.guild.id]
Note: Make sure that
ctx.guild.id
variable is of typestr
else it won't work.注意:确保ctx.guild.id
变量是str
类型,否则它将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.