翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$hour
$hour 演算子は、日付またはタイムスタンプフィールドから時間コンポーネントを抽出します。
パラメータ
-
dateExpression: 演算子が適用される日付。これは有効な BSON 日付 (例: $createdAt のようなフィールドや日付リテラル) に解決する必要があります。
パラメータは、次の形式でドキュメントとして指定することもできます。
{ 日付: <dateExpression>、タイムゾーン: <timezoneExpression> }
これにより、 はタイムゾーン対応の日付オペレーションを適用できます。
- `<tzExpression>`: (optional) The timezone of the operation result. It must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If no timezone is provided, the result is in UTC.
例 (MongoDB シェル)
次の例は、 $hour演算子を使用して日付フィールドから時間コンポーネントを抽出し、それに応じてデータをグループ化する方法を示しています。
サンプルドキュメントを作成する
db.events.insertMany([ { timestamp: new Date("2023-04-01T10:30:00Z") }, { timestamp: new Date("2023-04-01T12:45:00Z") }, { timestamp: new Date("2023-04-02T08:15:00Z") }, { timestamp: new Date("2023-04-02T16:20:00Z") }, { timestamp: new Date("2023-04-03T23:59:00Z") } ]);
クエリの例
db.events.aggregate([ { $project: { hour: { $hour: "$timestamp" } } }, { $group: { _id: "$hour", count: { $sum: 1 } } }, { $sort: { _id: 1 } } ]);
出力
[
{ "_id": 8, "count": 1 },
{ "_id": 10, "count": 1 },
{ "_id": 12, "count": 1 },
{ "_id": 16, "count": 1 },
{ "_id": 23, "count": 1 }
]
このクエリは、 timestampフィールドの時間コンポーネントでイベントをグループ化し、1 時間あたりのイベント数をカウントします。
コードの例
$hour コマンドを使用するためのコード例を表示するには、使用する言語のタブを選択します。