MongoDB 如何使用文档数组中的元素数更新计数字段

MongoDB how to update a count field with the number of elements that are in an array on the document

我想更新 Post 模型中的字段。 Post 模型如下所示:

const postSchema = new Schema({
  title: {
  }
  likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}],
  upvotes: {
    type: Number,
    default: 0
  }
})

我有一个 posts 的数据库,我想 update 通过计算它们的 likes(存储的 ID)和 update upvotes 到文档中的点赞数。有没有办法做到这一点?我可以使用 Mongo shell.

对于 Mongo 版本 4.2+,您可以使用 pipelined updates 来执行此操作,如下所示:

db.collection.updateMany(
{},
[
  {
    $set: {
      upvotes: {
        $size: "$likes"
      }
    }
  }
])

Mongo Playground

对于较小的 Mongo 版本,您必须将每个文档读入内存,并为其执行更新。