$abs - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$abs

Amazon DocumentDB 中的$abs运算符返回数字的绝对值。它可以在聚合管道中用于对数值字段执行数学运算。

参数

  • number:将返回其绝对值的数值表达式。

示例(MongoDB 外壳)

此示例演示如何使用$abs运算符来查找数值字段的绝对值。

创建示例文档

db.numbers.insertMany([ { "_id": 1, "value": -5 }, { "_id": 2, "value": 10 }, { "_id": 3, "value": -3.14 }, { "_id": 4, "value": 0 } ]);

查询示例

db.numbers.aggregate([ { $project: { "_id": 1, "absolute_value": { $abs: "$value" } }} ]);

输出

[ { "_id": 1, "absolute_value": 5 }, { "_id": 2, "absolute_value": 10 }, { "_id": 3, "absolute_value": 3.14 }, { "_id": 4, "absolute_value": 0 } ]

代码示例

要查看使用该$abs命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function main() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('numbers'); const result = await collection.aggregate([ { $project: { "_id": 1, "absolute_value": { $abs: "$value" } }} ]).toArray(); console.log(result); await client.close(); } main();
Python
from pymongo import MongoClient def main(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['numbers'] result = list(collection.aggregate([ { '$project': { "_id": 1, "absolute_value": { "$abs": "$value" } }} ])) print(result) client.close() if __name__ == "__main__": main()