在 mongoose / mongo 中管理大型 ObjectID 数组的最佳方法是什么

问题描述

在这种情况下:

const PostSchema = new mongoose.Schema({
    "content": {
        type: String,required: true
    },"user": {
        type: mongoose.Schema.Types.ObjectId,required: true,ref: "User"
    },"created": {
        type: Date,default: Date.now()
    },"comments": [{
        type: mongoose.Schema.Types.ObjectID,ref: 'Comment'
    }]
})

我希望能够一次获得 10 条评论,但我认为没有办法做到这一点,而不必每次都获得所有评论。

解决方法

您可以使用 uncorrelated lookup 来加入集合并限制为 10 个。这是一个示例,为了便于理解,我将 String 用于 _id

  • $lookup - 有两个查找,我在这里使用了不相关查找,您可以在加入集合中进行并行聚合。 $match 有助于有条件地连接文档。当您使用不相关查找时,必须在 $expr 中使用 $match$limit 有助于限制文档。如果需要,您可以添加更多阶段以在管道内执行聚合

这是脚本

db.PostSchema.aggregate([
  {
    "$lookup": {
      "from": "Comment",let: {
        cId: "$comments"
      },"pipeline": [
        {
          $match: {
            $expr: {
              _id: {
                in: [
                  "$$cId"
                ]
              }
            }
          }
        },{
          $limit: 10
        }
      ],"as": "comments"
    }
  }
])

工作Mongo playground

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...