简体   繁体   English

在 Python 中的字典中搜索列表 - Pymongo

[英]Searching in a list inside a dict in Python - Pymongo

Hope everybody is doing just fine.希望每个人都做得很好。

I've stored data with Mongodb with the following structure:我用 Mongodb 存储了具有以下结构的数据:

{'_id': ObjectId('5f788e29d55317c9cedf2'), 'num': '5512', 'person': [['John', 'Leader'], ['Mary', 'Follower']], 'valid': True}

I'm trying to search for string within the key "person", but with no success so far.我正在尝试在键“person”中搜索字符串,但到目前为止没有成功。

Here is the code I'm using:这是我正在使用的代码:

name = "John"
rgx = re.compile('.*(%s).*'%name, re.IGNORECASE)
selection = db.collection.find({"person": rgx})

But it returns empty everytime.但它每次都返回空。

Any ideas on why and what I'm doing wrong?关于为什么以及我做错了什么的任何想法?

Thanks a lot!非常感谢!

I would recommend you change your data model, otherwise your queries are going to be a world of pain.我建议你改变你的数据模型,否则你的查询将是一个痛苦的世界。 But if you can't, this query would work using the $elemMatch operator :但如果你不能,这个查询将使用$elemMatch操作符

print(list(db.mycollection.find({'person': {'$elemMatch': {'$elemMatch': {'$in': ['John']}}}})))

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

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