Javascript MongoDB:嵌套聚合

Javascript MongoDB:嵌套聚合,javascript,mongodb,mongoose,nosql,Javascript,Mongodb,Mongoose,Nosql,我有多个收藏: 用户-集合架构 { _id: 5fc5faaa8b1fffc1f4dec900, title: "hello there", author: 5fc531cae70f776378cce0c4 // Author is related to user collection }, { _id: 5fc5f3e6140646c2024f7963, title: "hello wonderland", autho

我有多个收藏:

用户-集合架构

{
   _id: 5fc5faaa8b1fffc1f4dec900,
   title: "hello there",
   author: 5fc531cae70f776378cce0c4 // Author is related to user collection
},
{
   _id: 5fc5f3e6140646c2024f7963,
   title: "hello wonderland",
   author: 5fc531cae70f776378cce0c4 // Author is related to user collection
}
历史记录是用户集合/文档的子文档

name: "jacob"
_id: 5fc53209e70f776378cce0c5,
history: [
  {
     _id: 5fc634bee65f96338a63b9e4,
     article: 5fc5f3e6140646c2024f7963,
     created_at: 2010-12-01T12:19:10.121+00:00
  },
  {
    _id: 5fc634d8e65f96338a63b9e5,
    article: 5fc5faaa8b1fffc1f4dec900,
    created_at: 2010-12-01T12:19:36.102+00:00
  }
]
文章-集合模式

{
   _id: 5fc5faaa8b1fffc1f4dec900,
   title: "hello there",
   author: 5fc531cae70f776378cce0c4 // Author is related to user collection
},
{
   _id: 5fc5f3e6140646c2024f7963,
   title: "hello wonderland",
   author: 5fc531cae70f776378cce0c4 // Author is related to user collection
}
是否可以
$lookup
历史记录中的文章,然后
$lookup
文章的作者?还有按历史日期排序

所需输出

...
name: "jacob",
_id: 5fc53209e70f776378cce0c5,
history: [
  {
     _id: 5fc634bee65f96338a63b9e4,
     article: {
        _id: 5fc5faaa8b1fffc1f4dec900,
        title: "hello there",
        author: {
           _id: 5fc531cae70f776378cce0c4,
           name: "melissa"
        }
     },
     created_at: 2010-12-01T12:19:10.121+00:00
  },
  {
    _id: 5fc634d8e65f96338a63b9e5,
    article: {
       _id: 5fc5faaa8b1fffc1f4dec900,
       title: "hello wonderland",
       author: {
          _id: 5fc531cae70f776378ccedsu8,
         name: "omelia",
       }
    },
    created_at: 2010-11-12T2:19:36.102+00:00
  }
]
注:按日期降序排序

你可以试试

  • $unwind
    解构
    历史
    数组
  • $lookup
    加入文章集合,让我们传递文章id,
    • $match
      匹配文章id
    • $lookup
      加入用户集合
    • $unwind
      解构用户,因为其数组
    • $project
      显示必填字段
  • $unwind
    解构文章数组
  • $sort
    日期创建
  • $group
    按id并重建
    历史
    数组
你可以试试

  • $unwind
    解构
    历史
    数组
  • $lookup
    加入文章集合,让我们传递文章id,
    • $match
      匹配文章id
    • $lookup
      加入用户集合
    • $unwind
      解构用户,因为其数组
    • $project
      显示必填字段
  • $unwind
    解构文章数组
  • $sort
    日期创建
  • $group
    按id并重建
    历史
    数组