$minute - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$minute

Amazon DocumentDB $minute 中的彙總管道階段會從日期或時間戳記欄位中擷取分鐘值。

當您需要在彙總管道中執行日期和時間型計算或分組時,此運算子非常有用。

參數

  • expression:要從中擷取分鐘值的日期或時間戳記欄位。

範例 (MongoDB Shell)

下列範例示範如何使用 $minute運算子,依從時間戳記欄位擷取的分鐘值將文件分組,並計算每個群組中的文件數量。

建立範例文件

db.events.insertMany([ { timestamp: new Date("2023-04-15T10:30:25.000Z") }, { timestamp: new Date("2023-04-15T10:30:35.000Z") }, { timestamp: new Date("2023-04-15T10:31:05.000Z") }, { timestamp: new Date("2023-04-15T10:31:45.000Z") }, { timestamp: new Date("2023-04-15T10:32:15.000Z") } ]);

查詢範例

db.events.aggregate([ { $group: { _id: { minute: { $minute: "$timestamp" } }, count: { $count: {} } } }, { $sort: { "_id.minute": 1 } } ]);

輸出

[ { "_id": { "minute": 30 }, "count": 2 }, { "_id": { "minute": 31 }, "count": 2 }, { "_id": { "minute": 32 }, "count": 1 } ]

程式碼範例

若要檢視使用 $minute命令的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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('events'); await collection.insertMany([ { timestamp: new Date("2023-04-15T10:30:25.000Z") }, { timestamp: new Date("2023-04-15T10:30:35.000Z") }, { timestamp: new Date("2023-04-15T10:31:05.000Z") }, { timestamp: new Date("2023-04-15T10:31:45.000Z") }, { timestamp: new Date("2023-04-15T10:32:15.000Z") } ]); const result = await collection.aggregate([ { $group: { _id: { minute: { $minute: "$timestamp" } }, count: { $count: {} } } }, { $sort: { "_id.minute": 1 } } ]).toArray(); console.log(result); await client.close(); } example();
Python
from pymongo import MongoClient from datetime import datetime def example(): 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['events'] collection.insert_many([ {'timestamp': datetime(2023, 4, 15, 10, 30, 25)}, {'timestamp': datetime(2023, 4, 15, 10, 30, 35)}, {'timestamp': datetime(2023, 4, 15, 10, 31, 5)}, {'timestamp': datetime(2023, 4, 15, 10, 31, 45)}, {'timestamp': datetime(2023, 4, 15, 10, 32, 15)} ]) result = list(collection.aggregate([ { '$group': { '_id': { 'minute': {'$minute': '$timestamp'} }, 'count': {'$count': {}} } }, {'$sort': {'_id.minute': 1}} ])) print(result) client.close() example()