简体   繁体   中英

pymongo where clause with a complex function

How do I write the below search query using 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. Here's a complete example, notice how I wrap the Javascript in triple-quotes:

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)"""}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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