0

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

}}

Veena
  • 105
  • 9

1 Answers1

1

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)"""}))
A. Jesse Jiryu Davis
  • 22,038
  • 3
  • 48
  • 64
  • Thanks for the reply Jesse, I tried the above, but I need to send the value "2" in return deepIterate(this, 2). I get this value as function variable and need to have this collection.find_one as a statement in that function. Tried %s and sending the value, it didn't help. – Veena Aug 29 '17 at 12:40