mongodb - 使用第一个集合 id 从另一个集合中获取总数
问题描述
我有两个系列。
第一个 id pod具有以下结构:
{
"_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 没有任何成员结果,我也需要每个pod的total_members代表返回 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 }]
解决方案
我会稍微改变你的聚合,所以你不需要使用$group
舞台。用于$size
获取 total_members 而不是$sum
. 用以下阶段替换之后$lookup
的阶段。
{"$addFields":{
"total_members":{
"$size":{
"$filter":{
"input":"$meminfo",
"as":"mi",
"cond":{"$gt":["$$mi.datetime",null]}
}
}
}
}},
{"$project":{"meminfo":0}},
{"$addFields":{"Status":false}}
推荐阅读
- javascript - 如何使用useRef钩子去除useEffect的效果?
- javascript - 如何过滤数组以仅在 Google Apps 脚本/Javascript 中完全匹配
- html - 选项卡列表和选项卡内容之间的空格
- mysql - 按最后一次出现分组
- php - Laravel:使用 where inside(带模型)
- c# - 如何防止 WMPLib.WindowsMediaPlayer 在计算机休眠时停止播放音乐?
- r - 如何从其 cdf 不是封闭形式的分布中生成数据?
- spring-boot - Spring Boot webflux - 验证配置属性
- google-sheets - 谷歌表格上流通股的历史数据
- elasticsearch - 使用 axios elasticsearch 发布 bulk.json