mongodb - MongoDB Self Join 并从文档数组中仅选择子项
问题描述
我有如下数据
[
{
"_id": 1,
"members": [
"a1",
"a2"
],
"member_profiles": [
{
"_id": "a1",
"is_removed": true
}
]
},
{
"_id": 2,
"members": [
"a1",
"a3"
],
"member_profiles": [
{
"_id": "a3",
"is_removed": true
}
]
}
]
我只想从文档中选择那些没有is_removed
标志“真”的成员
所以上面的查询应该["a2"]
从第一个文档和["a1"]
第二个文档中给我。
最后,我想通过分组将所有这些成员 ID 放在一个集合中,但我被困在如何进行文档级过滤
提前致谢
解决方案
演示 - https://mongoplayground.net/p/WlWhxJtZn1D
db.collection.aggregate([
{ $unwind: "$member_profiles" }, // member_profiles into individual documents
{ $match: { "member_profiles.is_removed": true } }, // filter only is_removed is true
{ $group: { "_id": "$_id", members: { "$first": "$members" }, member_profiles: { "$push": "$member_profiles" } } }, // group records back
{
$project: {
"activeMembers": {
$filter: { // to remove null values
input: {
"$map": {
"input": "$members",
"as": "m",
"in": {
"$cond": {
"if": { "$in": [ "$$m", "$member_profiles._id" ] }, // find if current member in member_profiles._id is there
"then": "$$m",
"else": null }
}
}
},
as: "mem",
cond: { $ne: [ "$$mem", null ] }
}
}
}
}
])
输出
[
{
"_id": 2,
"activeMembers": [
"a1"
]
},
{
"_id": 1,
"activeMembers": [
"a2"
]
}
]
推荐阅读
- r - 如何告诉马赛克(马赛克图,R,VCD包)即使在使用残余阴影时也总是打印p值?
- github-actions - 如何在 GitHub Actions 工作流程中进行 apt-get install?
- python - 如何将 abc.MutableMapping 的实现注册为 dict 子类?
- python - 如何按熊猫中的csv文件名索引列表?
- julia - 在 Julia 中绘制函数
- python - 如何展平具有以下内容的列表:原始数据类型、列表和生成器?
- metaprogramming - 你如何从它们所属的类型之外访问私有方法或属性?
- html - 如何将标签或段落准确地放在/绑定项目顶部?
- javascript - Javascript if/else 不工作。奥丁项目的石头剪刀布
- performance - 如何检查 Z3 优化问题的进度