如何使用pymongo编写以下搜索查询?这个查询在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")
}}
答案 0 :(得分: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)"""}))