有一个代理表 - 每个代理可以有多个用户 我想要 users[] 数组,但只有有限的字段
这个有效,但它把太多的信息放入 users[] 数组......
agencyTable.aggregate([
{
$match: {}
},
{
$sort: {
activityDate: 1
}
},
{
$lookup: {
from: "users",
localField: "_id",
foreignField: "agency",
as: "users"
}
},
{ $unwind: "$users" },
{ $match: { 'users.type': 'agent' } },
{
$group: {
"_id": "$_id",
"phone": { "$first": "$phone" },
"activityDate": { "$first": "$activityDate" },
"users": { "$push": "$users" }
}
},
{
$project: {
"_id" : 1,
"phone" : 1,
"activityDate" : 1,
"users" : 1
// "userID" : "$users._id",
// "userName" : "$users.name",
// "userPhone" : "$users.phone",
}
}]
然后我尝试取消注释较低的 3 行,但随后发生了一些奇怪的事情......
vm.agencyRecord : [
{
"_id": "Mic Agency Ltd",
"phone": "ZZZZ",
"activityDate": 1521460192,
"userID": [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
],
"userName": [
"Michael Agent",
"Nana Banana",
"Gogo Banana",
"Wollah Woldsom",
"weqweqweqwe",
"werwer"
],
"userPhone": [
"99 22 99 22 33",
"111 222 999",
"111 222 999",
"234234234",
"34234234234",
"werwerwer"
]
},
因为那不是我想要的。我想保留相同的用户数组,但字段要少得多。
那有可能吗?
使用$map
限制领域。
$$
访问usr
用户变量以引用元素的语法,然后是您希望保留的字段映射。
就像是
{
"$project":{
"_id":1,
"phone":1,
"activityDate":1,
"users":{
"$map":{
"input":"$users",
"as":"usr",
"in":{
"userID":"$$usr._id",
"userName":"$$usr.name",
"userPhone":"$$usr.phone"
}
}
}
}
}
您可以使用$addFields
stage 而不是$project
stage来简化聚合。
{
"$addFields":{
"users":{
"$map":{
"input":"$users",
"as":"usr",
"in":{
"userID":"$$usr._id",
"userName":"$$usr.name",
"userPhone":"$$usr.phone"
}
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句