I didn't pay attention to using JavaScript to manage MongoDB in the past, but this is a useful function. In particular, you can write some scheduled scripts, regularly check the database, and perform some management tasks.
1. mongo shell can directly run JavaScript code
For example:
> 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 () and Date () are not the same thing. Refer
Http://stackoverflow.com/questions/3505693/difference-between-datedatestring-and-new-datedatestring
To obtain the number of milliseconds since epoch, you must use new Date ().
Date () is just a function that returns a string. It does not play a major role, but it is easy to confuse the concept of people.
B. The Date object provides getTime ()
2. You can use $ where operator to execute JavaScript Functions in the query statement. For example:
db.display.find({$and: [{$where: function() {return new Date().getTime() / 1000 - this.last_active_time > 300}}, {status: "offline"}]})
$ Where references: http://docs.mongodb.org/manual/reference/operator/query/where/
3. You can write the code to a js file and run the mongo command.
For example, if the difference between the current time and the value of the last_active_time field is greater than 300 seconds, the document with the status of offline is found and displayed.
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());}
Run the following command:
mongo localhost/mydb test.js