$literal (aggregation)

    在本页面

    定义

    $literal

    返回 value 而不解析。用于聚合管道可以将其解释为表达式的值。

    $literal表达式具有以下语法:

    1. { $literal: <value> }

    行为

    如果<value>是表达,$literal不会计算表达式,而是返回未解析的表达式。

    结果
    { $literal: { $add: [ 2, 3 ] } } { “$add“ : [ 2, 3 ] }
    { $literal: { $literal: 1 } } { “$literal“ : 1 }

    例子

    将$视为文字

    在表达中,美元符号$评估为字段路径; 即:提供对该字段的访问。对于 example,$eq expression $eq: [ “$price“, “$1“ ]在名为price的字段中的 value 与文档中名为1的字段中的 value 之间执行相等性检查。

    以下 example 使用$literal表达式将包含美元符号“$1“的 string 视为常量 value。

    集合records具有以下文档:

    1. { _id : 1, item : abc123“, price: $2.50 }
    2. { _id : 2, item : xyz123“, price: 1 }
    3. { _id : 3, item : ijk123“, price: $1 }
    1. db.records.aggregate( [
    2. { $project: { costsOneDollar: { $eq: [ $price“, { $literal: $1 } ] } } }
    3. ] )

    此操作投影名为costsOneDollar的字段,该字段包含 boolean value,指示price字段的 value 是否等于 string “$1“

    1. { _id : 1, costsOneDollar : false }
    2. { _id : 2, costsOneDollar : false }
    3. { _id : 3, costsOneDollar : true }

    使用 Value 1 投影新字段

    $project阶段使用表达式<field>: 1在输出中包含<field>。以下 example 使用$literal来_return 将新字段设置为1的 value。

    集合bids具有以下文档:

    1. { _id : 1, item : abc123“, condition: new }
    2. { _id : 2, item : xyz123“, condition: new }

    以下聚合计算表达式item: 1以表示 return 输出中的现有字段item,但使用{$literal:1 }表达式 return 新字段startAt设置为 value 1

    1. db.bids.aggregate( [
    2. { $project: { item: 1, startAt: { $literal: 1 } } }
    3. ] )

    该操作产生以下文件:

    1. { _id : 1, item : abc123“, startAt : 1 }
    2. { _id : 2, item : xyz123“, startAt : 1 }