[英]pymongo where clause with a complex function
如何使用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")
}}
您可以通過將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)"""}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.