【问题标题】:MongoDB: Nested aggregationMongoDB:嵌套聚合
【发布时间】:2021-03-13 12:38:26
【问题描述】:

我有多个收藏:

用户 - 集合架构

历史是用户集合/文档的子文档

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
  }
]

注意:按日期降序排列

【问题讨论】:

    标签: javascript mongodb mongoose nosql


    【解决方案1】:

    你可以试试,

    • $unwind解构history数组
    • $lookup加入文章收藏,让传递文章id,
      • $match 匹配文章ID
      • $lookup加入用户收藏
      • $unwind 解构用户,因为它的数组
      • $project 显示必填字段
    • $unwind解构文章数组
    • $sort by created_at 日期
    • $group 按 id 并重构 history 数组
    db.users.aggregate([
      { $unwind: "$history" },
      {
        $lookup: {
          from: "articles",
          let: { articleId: "$history.article" },
          pipeline: [
            { $match: { $expr: { $eq: ["$_id", "$$articleId"] } } },
            {
              $lookup: {
                from: "users",
                localField: "author",
                foreignField: "_id",
                as: "author"
              }
            },
            { $unwind: "$author" },
            {
              $project: {
                _id: 1,
                author: { _id: 1, name: 1 },
                title: 1
              }
            }
          ],
          as: "history.article"
        }
      },
      { $unwind: "$history.article" },
      { $sort: { "history.created_at": -1 } },
      {
        $group: {
          _id: "$_id",
          history: { $push: "$history" },
          name: { $first: "$name" }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 2017-07-16
      • 2019-07-20
      • 1970-01-01
      • 2021-03-19
      • 2021-12-02
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多