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

Time:04-03

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.

CodePudding user response:

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.

  • Related