$floor - Amazon DocumentDB

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

$floor

4.0 版的新增内容。

Amazon DocumentDB 中的$floor运算符返回小于或等于指定数字的最大整数。此运算符对于向下舍入数值很有用。

参数

  • expression: 要向下舍入的数值表达式。

示例(MongoDB 外壳)

以下示例演示如何使用$floor运算符将十进制值向下舍入到最接近的整数。

创建示例文档

db.numbers.insertOne({ value: 3.14 });

查询示例

db.numbers.aggregate([ { $project: { _id: 0, floored: { $floor: "$value" } } } ]);

输出

{ "floored" : 3 }

代码示例

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

Node.js
const { MongoClient } = require('mongodb'); async function example() { const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('test'); const collection = db.collection('numbers'); const result = await collection.aggregate([ { $project: { _id: 0, floored: { $floor: "$value" } } } ]).toArray(); console.log(result); } catch (error) { console.error('Error:', error); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from pprint import pprint def example(): client = None try: 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': 0, 'floored': { '$floor': '$value' }}} ])) pprint(result) except Exception as e: print(f"An error occurred: {e}") finally: if client: client.close() example()