python - 在嵌套数组 pymongo 中查找

标签 python mongodb pymongo

<分区>

我正在尝试查询 MongoDB 数据库以查找包含特定 ID 的所有结果:

我的架构如下所示:

_id: xyz
ad_accounts: [{"name":"abc, "ads:{"campaings":[123, 4456, 574]}}]

我需要在“campaigns”中找到所有包含 123 的结果

这是一个更好的模式图像:

DB Schema

我试过以下方法:

results = db.data.find({"ad_accounts.ads.campaigns": 123})

但它不起作用,因为 ad_accounts 是一个数组,我也尝试过循环:

for data in all_data:
    for account in data['ad_accounts']:
        if first_ad in account['ads']['campaigns]:
            print("this is the one")

但我认为这不是最好的。

是否有内置的方法来查询嵌套数据?谢谢

最佳答案

离开你的例子,你可以使用这个语法:

>>> for match in collec.find({ "ad_accounts.0.ads.campaigns" : { "$in" : [123] } }):
...     print(match)
...     
{'_id': ObjectId('5adcd32690542e05e121bbdd'), 'ad_accounts': [{'name': 'abc', 'ads': {'campaigns': [123, 4456, 574]}}]}

$in 是一个用于匹配数组中任意元素的命令。

用 pymongo 重现这个例子:

from pymongo import MongoClient

client = MongoClient()
test_db = client.test_db
collec = test_db.collec

val1 = {"ad_accounts": [{"name": "abc", "ads": {"campaigns": [123, 4456, 574]}}]}
val2 = {"ad_accounts": [{"name": "abc", "ads": {"campaigns": [999, 4456, 574]}}]}

collec.insert_many([val1, val2])

对于嵌套数组,您需要 elemMatch

关于python - 在嵌套数组 pymongo 中查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968701/

相关文章:

python - 如何使用 Python 在 lxml etree 上进行最佳迭代(广度优先)

python - 如何断言一个方法是用 python unittest 装饰的?

python - 带有 mpz/mpfr 值的 numpy 数组

MongoDB:验证集合中已存在的文档

flask - pymongo 中的唯一字段

python - 单元测试 : assert exception-handling function called

node.js - SailsJS 模型按条件计数

node.js - 通过在 mongoose 中填充匹配结果来查找文档

python-3.x - 名称解析暂时失败,mongo-sec :27017

sorting - pymongo sort() limit() 不同吗?