简体   繁体   English

如何使用 Pymongo 和 MongoDB 返回特定字段?

[英]How to return a specific fields using Pymongo and MongoDB?

I am trying to return just two fields from my MongoDB database and this query correct sends back my username and posts from the client:我试图从我的 MongoDB 数据库中返回两个字段,这个查询正确地从客户端发回我的用户名和帖子:

db.users.find({'email_address': /^johnny/}, {'username': 1, 'user_posts': 1, '_id': 0});

I'm trying to switch this to PyMongo so I can query in Python and my query looks like this:我正在尝试将其切换到 PyMongo,以便我可以在 Python 中查询,我的查询如下所示:

regx = Regex('^{0}'.format('johnny'))
query = {'postcode': regx}, {'username': 1, 'user_posts': 1, '_id': 0}
user_list = mycol.find(query).limit(5)

The bit where it's failing is here:它失败的地方在这里:

{'username': 1, 'user_posts': 1, '_id': 0}

As without this filter the documents are sent in full fine.由于没有此过滤器,文件将完全正常发送。 With that I get this error message from PyMongo:这样我就从 PyMongo 收到了这个错误信息:

TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping

I assume that my filter is malformed and it's no longer a dictionary so have tried various alternatives of wrapping in quotes and then.format() etc but cannot seem to hit the magical combination.我假设我的过滤器格式不正确,它不再是字典,因此尝试了用引号括起来然后使用 then.format() 等的各种替代方法,但似乎无法达到神奇的组合。

Turned out it was quite easy.. I just needed to have two dictionaries.原来这很容易..我只需要有两本字典。 1 for the query and the other for the filter. 1 个用于查询,另一个用于筛选。

regx = Regex('^{0}'.format('johnny'))
filter_stuff = {'username': 1, 'user_posts': 1, '_id': 0}

Then just build the full query as follows:然后按如下方式构建完整的查询:

user_list = mycol.find(query, filter_stuff).limit(5)

The problem is that the following is not a dictionary but a tuple of two dictionaries:问题是以下不是字典,而是两个字典的元组:

query = {'postcode': regx}, {'username': 1, 'user_posts': 1, '_id': 0}

if you wanted to use it directly you could do it with如果你想直接使用它,你可以用

user_list = mycol.find(query[0], query[1]).limit(5)

but probably best to actually assign it to two separate variables like so但可能最好像这样将它实际分配给两个单独的变量

query, filter = {'postcode': regx}, {'username': 1, 'user_posts': 1, '_id': 0}

and then接着

user_list = mycol.find(query, filter).limit(5)

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

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