本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$minute
Amazon DocumentDB 中的$minute聚合管道阶段从日期或时间戳字段中提取分钟值。
当您需要在聚合管道中执行基于日期和时间的计算或分组时,此运算符很有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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()