使用自己的字段过滤MongoDB

时间:2012-05-24 05:21:18

标签: python django mongodb

我正在尝试按照自己的字段过滤mongodb文档,特别是时间,即:

{time1: timeval1, time2: timeval2}

我希望能够得到一个结果集(比如.find()),其中timeval1大于timeval2。

我不知道怎么用$ gt做这个并且找不到类似的东西。关于如何做到这一点的任何想法?

我在djangi项目中从pymongo访问它...但我想要的只是mongodb查询。

1 个答案:

答案 0 :(得分:3)

您可以使用$where运算符和javascript表达式来编写查询逻辑。

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D

> db.newColl.find()

{ "_id" : ObjectId("4fbdcdd6e79d66d9e681b185"), "time1" : 123, "time2" : 22 }
{ "_id" : ObjectId("4fbdcddee79d66d9e681b186"), "time1" : 11, "time2" : 220 }
{ "_id" : ObjectId("4fbdcde6e79d66d9e681b187"), "time1" : 331, "time2" : 2120 }
{ "_id" : ObjectId("4fbdcdece79d66d9e681b188"), "time1" : 1, "time2" : 20 }

> db.newColl.find({'$where' : 'this.time1 > this.time2' });

{ "_id" : ObjectId("4fbdcdd6e79d66d9e681b185"), "time1" : 123, "time2" : 22 }


> db.newColl.find({'$where' : 'this.time1 < this.time2' });

{ "_id" : ObjectId("4fbdcddee79d66d9e681b186"), "time1" : 11, "time2" : 220 }
{ "_id" : ObjectId("4fbdcde6e79d66d9e681b187"), "time1" : 331, "time2" : 2120 }
{ "_id" : ObjectId("4fbdcdece79d66d9e681b188"), "time1" : 1, "time2" : 20 }