简体   繁体   中英

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:

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. Is there a way to do this? I can use the Mongo shell .

For Mongo version 4.2+ you can use pipelined updates to do this, like so:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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