关于这个问题的Here is the MongoPlayground
今天我有两个嵌套的object数组:

我有一系列的会议,里面有一系列的邀请。
我只需要项目的会议,但与PartnerId过滤的邀请。因此,我有许多不同合作伙伴的邀请,但当每个合作伙伴登录系统时,他只能看到自己的邀请,而不是其他人的邀请。换句话说,数组Invites将只有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
}
);发布于 2020-12-12 05:26:43
使用$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 "
]
}
}
}
}
}
])https://stackoverflow.com/questions/65258137
复制相似问题