JavaScript can be run in MongoDB Query

Source: Internet
Author: User
Tags mongodb query mongo shell

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.