mongodb - Mongo展开子对象和过滤器
问题描述
这是关于这个问题的 MongoPlayground
今天我有 2 个嵌套的对象数组:
我有一系列会议,其中有一系列邀请。
我只需要投影会议,但邀请由 PartnerId 过滤。所以我有很多不同伙伴的邀请,但是当每个伙伴登录到系统时,他只能看到自己的邀请,而看不到其他人的邀请。换句话说,数组 Invites 将只有对它的 PartnerId 的邀请。
我可以进入项目部分,但过滤掉我丢失的邀请。我应该对另一个数组使用 $filter 或 $group 吗?
这是我到目前为止得到的:
db.collection.aggregate([
{
"$match": {
"$nor": [
{
"Meetings": {
"$exists": false
}
},
{
"Meetings": {
"$size": 0.0
}
}
]
}
},
{
"$unwind": {
"path": "$Meetings"
}
},
{
"$project": {
"Meetings": "$Meetings"
}
},
{
"$replaceRoot": {
"newRoot": "$Meetings"
}
}
])
回答我做了...
db.getCollection("ClientProject").aggregate(
[
{
"$match" : {
"$and" : [
{
"PartnerIds" : {
"$in" : [
"5f9b247f0ca60a000232cacf"
]
}
},
{
"$nor" : [
{
"Meetings" : {
"$exists" : false
}
},
{
"Meetings" : {
"$size" : 0.0
}
},
{
"Meetings" : {
"$eq" : null
}
}
]
}
]
}
},
{
"$unwind" : {
"path" : "$Meetings"
}
},
{
"$project" : {
"Meetings" : "$Meetings"
}
},
{
"$replaceRoot" : {
"newRoot" : "$Meetings"
}
},
{
"$addFields" : {
"Invites" : {
"$filter" : {
"input" : "$Invites",
"as" : "invite",
"cond" : {
"$eq" : [
"$$invite.PartnerId",
"5f9b247f0ca60a000232cacf"
]
}
}
}
}
}
],
{
"allowDiskUse" : false
}
);
解决方案
使用$filter
是实现目标的好方法,您可以这样做:
db.collection.aggregate([
{
"$match": {
"$nor": [
{
"Meetings": {
"$exists": false
}
},
{
"Meetings": {
"$size": 0.0
}
}
]
}
},
{
"$unwind": {
"path": "$Meetings"
}
},
{
"$project": {
"invites": {
"$filter": {
"input": "$Meetings.Invites",
"as": "invite",
"cond": {
"$eq": [
"$$invite.PartnerName",
"Thiago Parceiro "
]
}
}
}
}
}
])
推荐阅读
- javascript - Javascript循环遍历多个表单,获取所有输入值
- c++ - 为什么我不能正确计算 C++ 中的大整数值?
- python - 点对多点的Python部署解决方案
- java - 使用并行流时的数据完整性
- r - 将具有重复值的列创建为多个数据框
- c# - 使用 TeamCity 自动将更改从父级传播到依赖自定义 NuGet 包
- django - 如何在 Wagtail Page.title 字段中提供默认值?
- javascript - 如何正确获取 iTunes API?
- laravel - 从 api 缓慢获取数据到 vue 视图的问题
- jestjs - 使用 jest 在 javascript 上测试实际返回值