我有两个收藏夹。
第一个ID 吊舱具有以下结构:
{
"_id": "5ae46c0aff1bde1634ad8b3f",
"admin": "595bdd5aa6ea2811d48a7802",
"name": "Fashion Trend",
"datetime": 1524919038771,
"approval": false,
"actions": "Comments",
"description": "Fashion is about dressing according to what's fashionable. Style is more about being yourself.",
"profilepic": "https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919188491.jpg",
"coverpic": "https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919171374.jpg",
"__v": 0
}
秒是 pod_members ,结构如下:
{
"_id": "5b127683187a4f19901e34b7",
"__v": 0,
"pod_id": "5ae470d04e15d607f043a20e",
"instaid": "5ad9a44cabd2180d64073462",
"username": "tagtor",
"user_id": "595bdd5aa6ea2811d48a7802",
"member_name": "Sagar Dalal",
"req_date": 1527936643123,
"datetime": 1527938142745,
"comments": ["Love the page. keep up the good job.", "Great job done with this page.", "Fabulous. ", "Keep up the great job. Well done. ", "Amazing instagram page. "]
}
每个 pod 我都需要 total_members ,如果pod没有任何成员结果,则应该代表返回0。
我的查询就像:
Pod.aggregate([
{
$lookup: {
from: "pod_members",
localField: "_id",
foreignField: "pod_id",
as: "meminfo"
}
},
{ $unwind: "$meminfo" },
{
$group: {
_id: "meminfo.pod_id",
total_members: { $sum: 1 }
}
},
{ $addFields: { "Status": false } }
]).exec(function (err, resp) {
if (err) console.log(err)
else console.log(resp)
})
但是它没有给我想要的结果。
我需要类似的结果
[{ _id: 5ae46c0aff1bde1634ad8b3f,
admin: 595bdd5aa6ea2811d48a7802,
name: 'Fashion Trend',
datetime: 1524919038771,
approval: false,
actions: 'Comments',
description: 'Fashion is about dressing according to what\'s fashionable. Style is more about being yourself.',
profilepic: 'https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919188491.jpg',
coverpic: 'https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919171374.jpg',
__v: 0,
total_members: 1,
Status: false }]
答案 0 :(得分:1)
我会稍微更改您的汇总,因此您不需要使用$group
阶段。使用$size
而不是$sum
来获取total_members。将$lookup
之后的阶段替换为以下阶段。
{"$addFields":{
"total_members":{
"$size":{
"$filter":{
"input":"$meminfo",
"as":"mi",
"cond":{"$gt":["$$mi.datetime",null]}
}
}
}
}},
{"$project":{"meminfo":0}},
{"$addFields":{"Status":false}}