【问题标题】:What's the best way to manage large ObjectID arrays in mongoose / mongo在 mongoose / mongo 中管理大型 ObjectID 数组的最佳方法是什么
【发布时间】:2021-04-22 10:02:52
【问题描述】:

在这种情况下:

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 个 cmets,但我认为如果不每次都获得所有 cmets 就没有办法做到这一点。

【问题讨论】:

  • 这个答案对你有帮助吗?

标签: mongodb mongoose pagination mongoose-schema mongoose-populate


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多