【问题标题】:MongoDB paginate 2 collections together on common fieldMongoDB 在公共字段上将 2 个集合分页
【发布时间】:2021-06-12 19:02:52
【问题描述】:

我有两个 mongo 集合 - FileFolder

两者都有一些共同的字段,如namecreatedAt 等。我有一个resources API,它返回一个包含来自两个集合的项目的响应,并添加了一个type 属性。 type 可以是filefolder

我想在这个列表中支持分页和排序,例如按createdAt排序。 aggregation 可以吗?如何实现?

将它们移动到容器集合不是首选选项,因为我必须在任一集合的每个 create/update/delete 上维护容器集合。

我也在使用猫鼬,如果它有任何实用功能或插件的话。

【问题讨论】:

    标签: mongodb mongoose pagination


    【解决方案1】:

    在这种情况下,您可以使用$unionWith。比如:

    Folder.aggregate([
      { $project: { name: 1, createdAt: 1 } },
      { 
        $unionWith: { 
          coll: "files", pipeline: [ { $project: { name: 1, createdAt: 1 } } ]
        } 
      },
      ... // your sorting go here
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      相关资源
      最近更新 更多