$where

在本页面

Definition

Important

在版本 3.6 中更改:$expr运算符允许在查询语言中使用aggregation expressions$expr$where快,因为它不执行 JavaScript,因此应首选使用。

Behavior

Restrictions

map-reduce operationsgroup命令和$where运算符表达式**无法访问mongoShell 程序中可用的某些全局函数或属性,例如db

下列 JavaScript 函数和属性**可用于map-reduce operationsgroup命令和$where运算符表达式:

Available Properties Available Functions
args

MaxKey
MinKey
assert()
BinData()
DBPointer()
DBRef()
doassert()
emit()
gc()
HexData()
hex_md5()
isNumber()
isObject()
ISODate()
isString()
Map()
MD5()
NumberInt()
NumberLong()
ObjectId()
print()
printjson()
printjsononeline()
sleep()
Timestamp()
tojson()
tojsononeline()
tojsonObject()
UUID()
version()

elemMatch

仅将$where查询运算符应用于顶级文档。 $where查询运算符将无法在嵌套文档中使用,例如,在$elemMatch查询中。

Considerations

使用普通的非$where查询语句具有以下性能优势:

Example

考虑players集合中的以下文档:

{
   _id: 12378,
   name: "Steve",
   username: "steveisawesome",
   first_login: "2017-01-01"
}
{
   _id: 2,
   name: "Anya",
   username: "anya",
   first_login: "2001-02-02"
}

以下示例使用$wherehex_md5() JavaScript 函数将name字段的值与 MD5 哈希值进行比较,并返回任何匹配的文档。

db.players.find( { $where: function() {
   return (hex_md5(this.name) == "9b53e667f30cd329dca1ec9e6a83e994")
} } );

该操作返回以下结果:

{
   "_id" : 2,
   "name" : "Anya",
   "username" : "anya",
   "first_login" : "2001-02-02"
}
首页