【问题标题】:pymongo where clause with a complex function具有复杂功能的 pymongo where 子句
【发布时间】:2018-02-01 07:48:57
【问题描述】:

如何使用 pymongo 编写以下搜索查询?这个查询在数据库中很适合我。

{$where: function() {
var deepIterate = function  (obj, value) {
    for (var field in obj) {
        if (obj[field] == value){
            return true;
        }
        var found = false;
        if ( typeof obj[field] === 'object') {
            found = deepIterate(obj[field], value)
            if (found) { return true; }
        }
    }
    return false;
};
return deepIterate(this, "573c79aef4ef4b9a9523028f")

}}

【问题讨论】:

    标签: mongodb pymongo pymongo-3.x pymongo-2.x


    【解决方案1】:

    您可以通过将 Javascript 代码作为字符串传递来在 PyMongo 中使用 $where 子句。这是一个完整的示例,请注意我如何将 Javascript 包装在三引号中:

    from pymongo import *
    
    client = MongoClient()
    db = client.test
    
    collection = db.collection
    collection.delete_many({})
    collection.insert_many([
        {"x": {"y": {"z": 1}}},
        {"x": {"y": {"z": 2}}},
    ])
    
    # A new request comes in with address "ip_2", port "port_2", timestamp "3".
    print(collection.find_one({
        "$where": """var deepIterate = function (obj, value) {
        for (var field in obj) {
            if (obj[field] == value){
                return true;
            }
            var found = false;
            if (typeof obj[field] === 'object') {
                found = deepIterate(obj[field], value)
                if (found) { return true; }
            }
        }
        return false;
    };
    
    return deepIterate(this, 2)"""}))
    

    【讨论】:

    • 感谢 Jesse 的回复,我尝试了上述方法,但我需要发送值“2”作为回报 deepIterate(this, 2)。我将此值作为函数变量获取,并且需要将此 collection.find_one 作为该函数中的语句。尝试 %s 并发送值,但没有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多