MongoDB/pymongo:在任意长度集合中检查一个未知键的字符串

发布于 2025-02-07 08:03:56 字数 962 浏览 1 评论 0原文

我想在集合中的一系列任意长度和键中搜索特定值。一个示例集合:

{
    'myJsonObject' : {
        'key1' : 'value1',
        'key2' : 'foobar',
        'key3' : 'value3'
    }
}

我想运行一个查询,该查询在 true 时才仅在任意数量的键/值对中找到字符串'foobar'。如果使用python dict,我会写一些类似的内容:

myJsonObject = {
    'key1' : 'value1',
    'key2' : 'foobar',
    'key3' : 'value3'
}

def check_for_foobar(aDict):
    for value in aDict.values():
        if 'foobar' == value:
            return(True)
    return(False)

print(check_for_foobar(myJsonObject))

在这种情况下,函数将返回true,因为foobar是其中之一。 是否有一种类似的方法来检查MongoDB或Pymongo中的任意长度和此类键的JSON对象的每个值?有人告诉我, $ elemmatch 操作员可能会有所帮助。 感谢您的任何帮助或指导。

I would like to search for a particular value in a series of key/value pairs of arbitrary length and keys in a collection. An example collection:

{
    'myJsonObject' : {
        'key1' : 'value1',
        'key2' : 'foobar',
        'key3' : 'value3'
    }
}

I want to run a query which returns True if and only if it finds the string 'foobar' in any of an arbitrary number of key/value pairs. If working with a python dict, I would write something like:

myJsonObject = {
    'key1' : 'value1',
    'key2' : 'foobar',
    'key3' : 'value3'
}

def check_for_foobar(aDict):
    for value in aDict.values():
        if 'foobar' == value:
            return(True)
    return(False)

print(check_for_foobar(myJsonObject))

In this case the function will return True because foobar is one of the values.
Is there an analogous way to check every value of a json object of arbitrary length and keys like this in mongodb or pymongo? I am told that the $elemMatch operator could be helpful.
Thank you for any help or guidance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文