Python中如何在代码里编写MongoDB的$where语句?

db.book.find( { $where: function() { ... return this._id % 100 == 0 ... } } ) 这样的 shell 在 python 里面应该怎么写?


Python中如何在代码里编写MongoDB的$where语句?
4 回复

传字符串…
“$where ”: “blablabla”


在Python的pymongo里,直接用$where操作符就行,参数是个JavaScript函数字符串。比如查集合里age字段大于25的文档:

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client['testdb']
collection = db['testcol']

# 用$where写JS函数字符串
result = collection.find({"$where": "function() { return this.age > 25; }"})

for doc in result:
    print(doc)

更简单的写法是用this直接比较:

result = collection.find({"$where": "this.age > 25"})

注意$where是全局扫描,数据量大时慢,能不用就不用。能用普通查询操作符(像$gt)就别用这个。

总结:$where里写JS字符串就行。

你只要记住传 dict 进去就知道怎么写了

但是我连最简单的这么写都是报错额? data = db.book.find({"$where":“lambda x:x”})
print(data[0])

回到顶部