MongoDB:从集合中获取每个文档

2024-06-16 11:54:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建一个discord bot。我正在使用MongoDB Atlas(NoSQL)

我有一个像这样的用户文档

"user": 12345,

"created_at": 2012-12-31 01:48:24

我想获取集合中的每个文档,然后获取它的created_at

我该怎么做?我试过用db.inv.find({}),但没用。我查看了MongoDB的文档,但他们只介绍了JavaScript。如何获取收藏中的每个文档


Tags: 文档dbmongodbbotfindjavascriptatnosql
2条回答

确保您的数据库是mongodb中的数据库。如果您的数据库是mongodb的client.db,那么您的代码是正确的

MONGODB_URI = "mongodb://user:password@host:port/"
client= pymongo.MongoClient(MONGODB_URI)
# database
db = client.db
# db.collection.find({}) will get the item list
result = db.inv.find({})

db.inv.find()将为您提供指向所有文档的游标对象,然后您需要迭代它返回的文档以获得指定的字段

确保已连接到正确的集合

result=db.inv.find()
for entry in result:
    print(entry["created_at"])

如果这对你有帮助,请告诉我

相关问题 更多 >