mongodb 嵌套展开并删除重复项

mongodb nested unwind and remove duplicates

我有一个用户collection

{
"_id":{"$oid":"61375acc1c7d0a1a6e6005f0"},
"fullName":"VishnuMohan",
"email":"vishnu@gmail.com",
"password":password,
"avatar":"avatar",
"friends":[],
"friendRequests":[]
}

和 posts collection 具有这种格式的文档

{
"_id":{"$oid":"613b725d68398c8f149db2e3"},
"postContent":"vishnu 1",
"medias":["medias.jped"],
"createdAt":{"$date":"2021-09-10T14:57:33.407Z"},
"userId":{"$oid":"61375acc1c7d0a1a6e6005f0"},
"authorName":"VishnuMohan",
"likes":[],
"comments":[]
}

我想获取每个用户的数据,包括 post 详细信息和其中的媒体

我尝试了使用查找的简单聚合,并且能够像这样获取用户的 post。

id:61375acc1c7d0a1a6e6005f0
fullName:"Vishnu Mohan"
email:"vishnu@gmail.com"
password:"b$Yrs5H3mYrM8xLwWlek3K7uAs.EOLsXggj6wV7oSflPlPjo1ZkFem6"
avatar:"https://avatars.dicebear.com/api/human/vishnu@gmail.com.svg"
friendRequests:Array
friends:Array
posts:[
{
_id:613b725d68398c8f149db2e3
postContent:"post 1"
medias:["media2.jpeg"]
createdAt:2021-09-10T14:57:33.407+00:00
userId:61375acc1c7d0a1a6e6005f0
authorName:"Vishnu Mohan"
avatar:"https://avatars.dicebear.com/api/human/vishnu@gmail.com.svg"
likes:Array
comments:Array
},
{
_id:613b725d68398c8fasdfgasdf
postContent:"post 2"
medias:["media3.jpeg","media4.jpeg"]
createdAt:2021-09-10T14:57:33.407+00:00
userId:61375acc1c7d0a1a6e6005f0
authorName:"Vishnu Mohan"
avatar:"https://avatars.dicebear.com/api/human/vishnu@gmail.com.svg"
likes:Array
comments:Array
}
]

现在我想展开 posts 数组并展开媒体并获得所需的输出:

id:61375acc1c7d0a1a6e6005f0
fullName:"Vishnu Mohan"
email:"vishnu@gmail.com"
password:"b$Yrs5H3mYrM8xLwWlek3K7uAs.EOLsXggj6wV7oSflPlPjo1ZkFem6"
avatar:"https://avatars.dicebear.com/api/human/vishnu@gmail.com.svg"
friendRequests:Array
friends:Array
posts:[
{
_id:613b725d68398c8f149db2e3
postContent:"post 1"
medias:["media2.jpeg"]
createdAt:2021-09-10T14:57:33.407+00:00
userId:61375acc1c7d0a1a6e6005f0
authorName:"Vishnu Mohan"
avatar:"https://avatars.dicebear.com/api/human/vishnu@gmail.com.svg"
likes:Array
comments:Array
},
{
_id:613b725d68398c8fasdfgasdf
postContent:"post 2"
medias:["media3.jpeg","media4.jpeg"]
createdAt:2021-09-10T14:57:33.407+00:00
userId:61375acc1c7d0a1a6e6005f0
authorName:"Vishnu Mohan"
avatar:"https://avatars.dicebear.com/api/human/vishnu@gmail.com.svg"
likes:Array
comments:Array
}
],
//new field named medias storing the values of medias array from all posts
medias:["media2.jpeg","media3.jpeg","media4.jpeg]

我正在寻找一种方法来从 posts 数组 objects 中的 medias 数组中获取值,并将其通过管道传输到外部的数组中。

查询

  • 减少从 [] 开始并连接所有帖子的媒体数组
  • 联合 [] 删除重复项(与每次连接相比,检查重复项 1 次更快)

Test code here

db.collection.aggregate([
  {
    "$set": {
      "medias": {
        "$setUnion": [
          {
            "$reduce": {
              "input": "$posts",
              "initialValue": [],
              "in": {
                "$concatArrays": [
                  "$$value",
                  "$$this.medias"
                ]
              }
            }
          },
          []
        ]
      }
    }
  }
])