[英]Get data from another collection using MongoDB
使用 MongoDB 我得到了銷售數據,我得到了銷售的客戶,但我只得到了他們的“_id”,但我需要得到他們的數據,比如名字。 這是可能的? 這是我對我的銷售集合所做的查詢,其中客戶是銷售對象:
db.sales.aggregate([
{
$group: {
_id: {
month: {
$month: "$createdAt"
},
year: {
$year: "$createdAt"
},
dayOfWeek: {
$dayOfWeek: "$createdAt"
},
stringDay: {
$dateToString:
{ format: "%Y-%m-%d", date: "$createdAt"}
},
week: {
$isoWeek: "$createdAt"
}
},
paymentType: { $first: '$paymentType' },
client: { $first: '$clientId' },
total: { $sum: '$total'},
count: { $sum: 1 },
totalAverage: { $avg: '$total'},
}
},
{
$project: {
total: { $round: [ "$total", 2 ] },
year: "$_id.year",
date: "$_id.date",
week: "$_id.week",
numVentas: "$count",
month: "$_id.month",
dayOfWeek: "$_id.dayOfWeek",
stringDay:"$_id.stringDay",
count: "$count",
paymentType: "$paymentType",
client: "$client",
totalAverage: { $round: [ "$totalAverage", 2 ] },
stringMonth: {
$arrayElemAt: [
[
"",
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"$_id.month"
]
},
stringWeek: {
$switch: {
branches:[
{ case: { $eq: ["$_id.dayOfWeek", 1] }, then: "Lunes" },
{ case: { $eq: ["$_id.dayOfWeek", 2] }, then: "Martes" },
{ case: { $eq: ["$_id.dayOfWeek", 3] }, then: "Miércoles" },
{ case: { $eq: ["$_id.dayOfWeek", 4] }, then: "Jueves" },
{ case: { $eq: ["$_id.dayOfWeek", 5] }, then: "Viernes" },
{ case: { $eq: ["$_id.dayOfWeek", 6] }, then: "Sábado" },
{ case: { $eq: ["$_id.dayOfWeek", 7] }, then: "Domingo" }
],
default: "Día desconocido"
}
}
}
},
{
$group: {
_id: { month: "$month", stringMonth: "$stringMonth", year: "$year"},
count: { $sum: "$count" },
total: { $sum: "$total" },
totalAverage: { $sum: "$totalAverage" },
sales: {
$push: {
client: "$client",
paymentType: "$paymentType",
numberDay: "$dayOfWeek",
week: "$week",
stringWeek: "$stringWeek",
date: "$stringDay",
total: "$total",
count: "$count",
totalAverage: { $round: [ "$totalAverage", 2 ] }
}
}
}
},
{
$group: {
_id: "$_id.year",
monthsWithSales: { $sum: 1 },
count: { $sum: "$count" },
total: { $sum: "$total" },
totalAverage: { $sum: "$totalAverage" },
sales: {
$push: {
month: "$_id.month",
stringMonth: "$_id.stringMonth",
count: "$count",
total: "$total",
totalAverage: "$totalAverage",
sales:"$sales"
}
}
}
}
])
這只給我帶來了銷售客戶的“_id”,但我還需要獲取其他數據,例如客戶集合中的客戶名稱:
"_id": 2022,
"monthsWithSales": 4,
"count": 57,
"total": 22324.8,
"totalAverage": 7765.799999999999,
"sales": [
{
"month": 12,
"stringMonth": "Dec",
"count": 33,
"total": 12587.6,
"totalAverage": 4074.5,
"sales": [
{
**"client": {
"$oid": "63890f616d8780e8608266f5"
},**
"paymentType": "CASH",
在 MongoDB 聚合中,您可以為此使用 Lookup 運算符。 參考:- 在 MongoDB 網站上閱讀 Lookup 。
如果您使用的是 Mongoose,您也可以使用Populate 方法。
如果它們有一個公共字段,這兩個都從另一個集合中獲取文檔並添加到當前集合中。 在這里討論可能會很復雜。 所以請參考官方文檔查找或填充
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.