Node.js Mongodb查找聚合未获取所有字段值
我有两个类似于模式的集合Node.js Mongodb查找聚合未获取所有字段值,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我有两个类似于模式的集合 driver _id:5f9c1d897ea5e246945cd73a agent_name:"Ratnabh Kumar Rai" agent_email:"ra2614@gmail.com" agent_phone:"70****63331" 及 因此,我想计算平均驾驶员等级。我尝试使用查找聚合,以便获得所有详细信息,然后再计算总和…我所做的是 let doc = await db .c
driver
_id:5f9c1d897ea5e246945cd73a
agent_name:"Ratnabh Kumar Rai"
agent_email:"ra2614@gmail.com"
agent_phone:"70****63331"
及
因此,我想计算平均驾驶员等级。我尝试使用查找聚合,以便获得所有详细信息,然后再计算总和…我所做的是
let doc = await db
.collection("drivers")
.aggregate([
{
$project: {
_id: {
$toString: "$_id",
},
},
},
{
$lookup: {
from: "reviews",
localField: "_id",
foreignField: "driver_id",
as: "driver_info",
},
},
{
$project: {
agent_email: 1,
orderReview: "$driver_info",
},
},
])
.toArray();
但我得到的结果是
{
_id: '5f9d63eb8737e82fbc193dd9',
orderReview: [ [Object], [Object], [Object], [Object], [Object] ]
}
这部分是正确的,因为我还需要从我的localfield集合(即drivers field)中获取详细信息,到目前为止,您可以看到我在投影中只获取驱动程序的id,我也做了“代理电子邮件:1”,但没有获取电子邮件,您实际上只在第一个管道中投影了id,因此只有id被传递到其他管道,如果你需要在更多的管道中发送电子邮件,你也需要将其投射出来
let doc = await db.collection("drivers").aggregate([
{
$project: {
_id: {
$toString: "$_id",
},
agent_email: "$agent_email"
},
},
{
$lookup: {
from: "reviews",
localField: "_id",
foreignField: "driver_id",
as: "driver_info",
},
},
{
$project: {
agent_email: 1,
orderReview: "$driver_info",
},
},
])
MongoDB游乐场:
[更新]
我意识到你这样做是为了得到平均值,如果你需要在一个聚合查询中得到平均值,这里是你如何做到的
使用“展开”操作符,可以将reviews数组展平为对象,然后按_id分组并使用$avg聚合操作符
db.collection("drivers").aggregate([
{
$project: {
_id: {
$toString: "$_id",
},
agent_email: "$agent_email"
},
},
{
$lookup: {
from: "reviews",
localField: "_id",
foreignField: "driver_id",
as: "driver_info",
},
},
// Makes the driver info flat with other information
{
"$unwind": "$driver_info"
},
{
// Now you can group them
$group: {
_id: "$_id",
// Calculates avg on rating field
avg: {
"$avg": "$driver_info.rating"
},
// To make email field appear in next pipeline.
// You can do it for other fields too like Name, etc
agent_email: {
$first: "$agent_email"
}
}
},
{
$project: {
// select the fields you want to display
agent_email: 1,
avg: 1
},
},
])
db.collection("drivers").aggregate([
{
$project: {
_id: {
$toString: "$_id",
},
agent_email: "$agent_email"
},
},
{
$lookup: {
from: "reviews",
localField: "_id",
foreignField: "driver_id",
as: "driver_info",
},
},
// Makes the driver info flat with other information
{
"$unwind": "$driver_info"
},
{
// Now you can group them
$group: {
_id: "$_id",
// Calculates avg on rating field
avg: {
"$avg": "$driver_info.rating"
},
// To make email field appear in next pipeline.
// You can do it for other fields too like Name, etc
agent_email: {
$first: "$agent_email"
}
}
},
{
$project: {
// select the fields you want to display
agent_email: 1,
avg: 1
},
},
])