简体   繁体   English

pymongo where子句具有复杂功能

[英]pymongo where clause with a complex function

How do I write the below search query using pymongo? 如何使用pymongo编写以下搜索查询? This query works well for me in the db. 该查询在数据库中对我来说效果很好。

{$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")

}} }}

You can use $where clauses in PyMongo by passing the Javascript code as a string. 您可以通过将Javascript代码作为字符串传递来在PyMongo中使用$ where子句。 Here's a complete example, notice how I wrap the Javascript in triple-quotes: 这是一个完整的示例,请注意我如何将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)"""}))

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

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