欢迎投稿

今日深度:

MongoDB查询中可以运行JavaScript

MongoDB查询中可以运行JavaScript


以前并没有留意用JavaScript管理MongoDB,不过这个还是很有用的功能。特别是可以写一些定时脚本,定期检查数据库,做一些管理任务。

1. mongo shell中可以直接运行JavaScript代码

比如:

> new Date()
ISODate("2013-12-12T07:37:00.074Z")
> x = new Date();
ISODate("2013-12-12T07:37:05.724Z")
> x.getTime();
1386833825724
> var y = Date();
> y.getTime()
Thu Dec 12 15:37:26.805 TypeError: Object Thu Dec 12 2013 15:37:21 GMT+0800 (CST) has no method 'getTime'
> 

a. new Date() 和 Date()不是一回事,参考

http://stackoverflow.com/questions/3505693/difference-between-datedatestring-and-new-datedatestring

如果想获得epoch以来的毫秒数,必须用new Date()。

而Date(),似乎就只是一个函数,返回一个字符串而已。没什么大作用,反而容易混淆人的概念。

b. Date对象提供了getTime()

2. 查询语句中,可以用$where operator来执行JavaScript函数, 比如:

 db.display.find({$and: [{$where: function() {return new Date().getTime() / 1000 - this.last_active_time > 300}}, {status: "offline"}]})
$where参考文档:http://docs.mongodb.org/manual/reference/operator/query/where/

3. 可以将代码写到一个js文件中,然后用mongo命令执行

比如:下面将当前时间和last_active_time字段的值的差大于300秒的,状态为offline的document找出来,并显示。

cursor = db.display.find({$and: [{$where: function() {return new Date().getTime() / 1000 - this.last_active_time > 300}}, {status: "offline"}]})
while (cursor.hasNext()) {
   printjson(cursor.next());
}
然后这样执行:
mongo localhost/mydb test.js

www.htsjk.Com true http://www.htsjk.com/DB2/20167.html NewsArticle MongoDB查询中可以运行JavaScript 以前并没有留意用JavaScript管理MongoDB,不过这个还是很有用的功能。特别是可以写一些定时脚本,定期检查数据库,做一些管理任务。 1. mongo shell中可以直...
评论暂时关闭