发布于 2015-09-14 14:57:53 | 161 次阅读 | 评论: 0 | 来源: 网络整理
Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The $where provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection. Reference the document in the JavaScript expression or function using either this or obj .
警告
Consider the following examples:
db.myCollection.find( { $where: "this.credits == this.debits" } );
db.myCollection.find( { $where: "obj.credits == obj.debits" } );
db.myCollection.find( { $where: function() { return (this.credits == this.debits) } } );
db.myCollection.find( { $where: function() { return obj.credits == obj.debits; } } );
Additionally, if the query consists only of the $where operator, you can pass in just the JavaScript expression or JavaScript functions, as in the following examples:
db.myCollection.find( "this.credits == this.debits || this.credits > this.debits" );
db.myCollection.find( function() { return (this.credits == this.debits || this.credits > this.debits ) } );
You can include both the standard MongoDB operators and the $where operator in your query, as in the following examples:
db.myCollection.find( { active: true, $where: "this.credits - this.debits < 0" } );
db.myCollection.find( { active: true, $where: function() { return obj.credits - obj.debits < 0; } } );
Using normal non-$where query statements provides the following performance advantages: