简体   繁体   English

如何将pymongo字段结果保存为字符串

[英]How to save pymongo field result as string

I'm new to pymgono and I'm trying to understand how to process results.我是 pymgono 的新手,我正在尝试了解如何处理结果。 I have the following code inside my Client class which inserts documents in a localhost mongodb:我的 Client 类中有以下代码,它在 localhost mongodb 中插入文档:

def InsertUser(self,
               userName: str,
               userDescription: str,
               userImage: str):
    # attempt to create or connect to users collection

    aUser = {"image_id": userImage,
             "name": userName,
             "description": userDescription}
    # insert randomly generated document into the database in the reviews collection
    result = self.myCollection.insert_one(aUser)

    print('Created:', aUser)
    print('at collection:', self.myCollection)
    print('with result:', result.inserted_id, '\n')

I then fetch specific fields using this method然后我使用此方法获取特定字段

def FindUser(self,
                 userName: str):
        print('found the following users named:',userName,'\n')
        myList=list()
        for i in self.myCollection.find({'name': userName},{'_id':0,'description':1}):
            myList.append(i)
        print('counted numbers in list=',len(myList))
        length=len(myList)
        for i in range(length):
            print(myList[i])

The find method prints myList[i] results as following: find 方法打印 myList[i] 结果如下:

counted numbers in list= 1
{'description': 'this is my description:'}

But what I really want to do is directly insert the description field into separate variable in string format like so:但我真正想做的是将描述字段直接插入到字符串格式的单独变量中,如下所示:

counted numbers in list= 1
this is my description

How do I do that?我怎么做? Thanks for your time.谢谢你的时间。

If I understand it correct userName should be unique for every user document in users collection, then using .find() would result in a single document in array, So instead of using .find() & iterating on it to get first document out of it, you can use .find_one() which would either return a single matched document or none if nothing matches with given filter :如果我理解正确的 userName 对于用户集合中的每个用户文档应该是唯一的,那么使用.find()将导致数组中的单个文档,因此而不是使用.find()并对其进行迭代以获取第一个文档它,您可以使用.find_one() ,如果没有与给定过滤器匹配的内容,它将返回单个匹配的文档或none

def FindUser(self,
             userName: str):
    print('finding the following user named:', userName, '\n')
    dBUserResp = self.myCollection.find_one({'name': userName}, {'_id': 0, 'description': 1}):
    if dBUserResp:
        print(dBUserResp.description)
    # Above will return a string 'this is my description:'

    if not dBUserResp:
        print('No user found in DB')

Note : I had given only positive scenario where you get a result out of DB operation but in general you need to edit your code to check for any error with DB calls itself..注意:我只给出了从 DB 操作中获得结果的正面场景,但通常您需要编辑代码以检查 DB 调用本身是否存在任何错误。

(Or) (或者)

If it's not the case & if you've multiple user documents with same userName then you can do :如果不是这种情况和如果你已经与同多个用户文档userName ,那么你可以这样做:

descriptionString = myList[i]['description']
print(descriptionString) # which prints the description as string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM