pymongo where clause with a complex function

3.5k Views Asked by At

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

}}

1

There are 1 best solutions below

2
A. Jesse Jiryu Davis On

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