0

如何使用 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")

}}

4

1 回答 1

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)"""}))
于 2017-08-23T16:11:53.573 回答