本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$month
Amazon DocumentDB 中的$month運算子會以 1 到 12 之間的數字傳回日期的月份。此運算子適用於從日期欄位擷取月份元件,以及執行以日期為基礎的彙總和分析。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $month運算子從日期欄位中擷取月份,並依月份分組資料。
建立範例文件
db.sales.insert([
{ product: "abc123", price: 10.99, date: new Date("2022-01-15") },
{ product: "def456", price: 15.50, date: new Date("2022-02-28") },
{ product: "ghi789", price: 8.25, date: new Date("2022-03-10") },
{ product: "jkl012", price: 12.75, date: new Date("2022-04-05") },
{ product: "mno345", price: 18.99, date: new Date("2022-05-20") }
]);
查詢範例
db.sales.aggregate([
{ $group: {
_id: { month: { $month: "$date" } },
totalSales: { $sum: "$price" }
}},
{ $sort: { "_id.month": 1 } }
]);
輸出
[
{ _id: { month: 1 }, totalSales: 10.99 },
{ _id: { month: 2 }, totalSales: 15.5 },
{ _id: { month: 3 }, totalSales: 8.25 },
{ _id: { month: 4 }, totalSales: 12.75 },
{ _id: { month: 5 }, totalSales: 18.99 }
]
程式碼範例
若要檢視使用 $month命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function groupSalesByMonth() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
try {
await client.connect();
const db = client.db('test');
const collection = db.collection('sales');
const pipeline = [
{
$group: {
_id: { month: { $month: "$date" } },
totalSales: { $sum: "$price" }
}
},
{
$sort: { "_id.month": 1 }
}
];
const results = await collection.aggregate(pipeline).toArray();
console.dir(results, { depth: null });
} finally {
await client.close();
}
}
groupSalesByMonth().catch(console.error);
- Python
-
from pymongo import MongoClient
def group_sales_by_month():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
try:
db = client.test
collection = db.sales
pipeline = [
{
"$group": {
"_id": { "$month": "$date" },
"totalSales": { "$sum": "$price" }
}
},
{
"$sort": { "_id": 1 }
}
]
results = collection.aggregate(pipeline)
for doc in results:
print(doc)
except Exception as e:
print(f"An error occurred: {e}")
finally:
client.close()
group_sales_by_month()