感谢https://stackoverflow.com/a/26436244/977828
,我有以下MongoDB查询var judge = function () {
var unexpect = "X";
var letter1 = unexpect, letter2 = unexpect;
for (var i in this.chr) {
var chr = this.chr[i];
if (chr.no == 5) {
letter1 = chr.letter;
} else if (chr.no == 6) {
letter2 = chr.letter;
}
}
if (letter1 != letter2 && letter1 != unexpect && letter2 != unexpect) {
return true;
}
return false;
};
db.sss.find({
"pos": { "$gte": 200000, "$lt": 2000000 },
"$where": judge
}, {"x_type":1, "sub_name":1, "name":1, "pos":1, "s_type":1, _id:0});
我尝试将上述查询移植到PyMongo,但我不知道将JavaScript函数放在何处。
from pymongo import MongoClient
db = MongoClient().test
sDB = db.sss
r = [["Test", "A", "B01", 828288, 1, 7, 'C', 4],
["Test", "A", "B01", 828288, 1, 7, 'C', 5],
["Test", "A", "B01", 828288, 1, 7, 'T', 6],
["Test", "A", "B01", 171878, 3, 8, 'C', 5],
["Test", "A", "B01", 171878, 3, 8, 'T', 6],
["Test", "A", "B01", 871963, 3, 9, 'A', 5],
["Test", "A", "B01", 871963, 3, 9, 'G', 6],
["Test", "A", "B01", 1932523, 1, 10, 'T', 4],
["Test", "A", "B01", 1932523, 1, 10, 'A', 5],
["Test", "A", "B01", 1932523, 1, 10, 'X', 6],
["Test", "A", "B01", 667214, 1, 14, 'T', 4],
["Test", "A", "B01", 667214, 1, 14, 'G', 5],
["Test", "A", "B01", 667214, 1, 14, 'G', 6]]
for i in r:
sDB.update({'type': i[0],
'name': i[1],
'sub_name': i[2],
'pos': i[3],
's_type': i[4],
'x_type': i[5]},
{"$push": {
"chr":{
"letter":i[6],
"no": i[7]} }},
True)
# var judge = function () {
# var unexpect = "X";
# var letter1 = unexpect, letter2 = unexpect;
# for (var i in this.chr) {
# var chr = this.chr[i];
# if (chr.no == 5) {
# letter1 = chr.letter;
# } else if (chr.no == 6) {
# letter2 = chr.letter;
# }
# }
# if (letter1 != letter2 && letter1 != unexpect && letter2 != unexpect) {
# return true;
# }
# return false;
# };
results = sDB.find({
"pos": { "$gte": 200000, "$lt": 2000000},
"$where": judge
},
{"x_type":1, "sub_name":1, "name":1, "pos":1, "s_type":1, "_id":0})
for i in results:
print i
如何将JavaScript函数集成到PyMongo?
答案 0 :(得分:1)
使用PyMongo,您应该能够将$where
的JavaScript作为字符串传递,例如像这样:
# JavaScript as multiline string
judge = """
function () {
var unexpect = "X";
var letter1 = unexpect, letter2 = unexpect;
for (var i in this.chr) {
var chr = this.chr[i];
if (chr.no == 5) {
letter1 = chr.letter;
} else if (chr.no == 6) {
letter2 = chr.letter;
}
}
if (letter1 != letter2 && letter1 != unexpect && letter2 != unexpect) {
return true;
}
return false;
};
"""
results = sDB.find({
"pos": { "$gte": 200000, "$lt": 2000000},
"$where": judge
},
{"x_type":1, "sub_name":1, "name":1, "pos":1, "s_type":1, "_id":0})