简体   繁体   English

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

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

I would like to update a field that I have on my Post model. The Post model looks like the following:我想更新我的Post model 中的一个字段。帖子 model 如下所示:

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

I have a database of posts that I would like to update by counting their likes (stored ID's) and update the upvotes to the number of likes in the document.我有一个posts数据库,我想通过计算他们的likes (存储的 ID)来update这些帖子,并将upvotes update为文档中的喜欢数量。 Is there a way to do this?有没有办法做到这一点? I can use the Mongo shell .我可以使用Mongo shell

For Mongo version 4.2+ you can use pipelined updates to do this, like so:对于 Mongo 4.2+ 版本,您可以使用流水线更新来执行此操作,如下所示:

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

Mongo Playground蒙戈游乐场

For lesser Mongo versions you'll have to read each document into memory, and execute an update for it.对于较小的 Mongo 版本,您必须将每个文档读入 memory,并为其执行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM