如何使用Mongodb Aggregate框架填充数据? [英] How to Populate data using Mongodb Aggregate framework?
问题描述
I have a current MongoDB Aggregate framework pipeline from a previous question and I am unable to add populate query to grab user profile by id.
我的代码在下面
Product.aggregate([
{
$group: {
_id: {
hub: "$hub",
status: "$productStatus",
},
count: { $sum: 1 },
},
},
{
$group: {
_id: "$_id.hub",
counts: {
$push: {
k: "$_id.status",
v: "$count",
},
},
},
},
{
$group: {
_id: null,
counts: {
$push: {
k: { $toString: "$_id" },
v: "$counts",
},
},
},
},
{
$addFields: {
counts: {
$map: {
input: "$counts",
in: {
$mergeObjects: [
"$$this",
{ v: { $arrayToObject: "$$this.v" } },
],
},
},
},
},
},
{
$replaceRoot: {
newRoot: { $arrayToObject: "$counts" },
},
},
]);
并得到以下结果
[
{
"5fe75679e6f7a62ddaf5b2e9": {
"in progress": 5,
"Cancelled": 4,
"return": 1,
"on the way": 3,
"pending": 13,
"Delivered": 4
}
}
]
预期产量
我需要使用 hubId
"5fe75679e6f7a62ddaf5b2e9"从用户集合中获取用户信息,并期望下面形式的最终结果
I need to grab user information from user collections using the hubId
"5fe75679e6f7a62ddaf5b2e9"
and expect a final result of the form below
[
{
"hub": {
"photo": "avatar.jpg",
"_id": "5fe75679e6f7a62ddaf5b2e9",
"name": "Dhaka Branch",
"phone": "34534543"
},
"statusCounts": {
"in progress": 5,
"Cancelled": 4,
"return": 1,
"on the way": 3,
"pending": 13,
"Delivered": 4
}
}
]
第一个ID是用户ID,可在用户集合中使用.
First id is user id and available in user collections.
推荐答案
You need to tweak your aggregate pipeline a little bit and include new pipeline stage like $lookup
that populates the
hub
Product.aggregate([
{ "$group": {
"_id": {
"hubId": "$hubId",
"status": "$productStatus"
},
"count": { "$sum": 1 }
} },
{ "$group": {
"_id": "$_id.hubId",
"statusCounts": {
"$push": {
"k": "$_id.status",
"v": "$count"
}
}
} },
{ "$lookup": {
"fron": "users",
"localField": "_id",
"foreignField": "_id",
"as": "user"
} },
{ "$project": {
"user": { "$arrayElemAt": ["$user", 0] },
// "hub": { "$first": "$hub" },
"statusCounts": { "$arrayToObject": "$statusCounts" }
} }
])
要仅投影用户个人资料中的某些字段,可以更新 $ lookup
管道具有表单
To project only some fields in the user profile, you can update your $lookup
pipeline to have the form
{ "$lookup": {
"from": "users",
"let": { "userId": "$_id" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": ["$_id", "$$userId"] }
} },
{ "$project": {
"name": 1,
"phone": 1,
"photo": 1
} }
],
"as": "user"
} }
这篇关于如何使用Mongodb Aggregate框架填充数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!