Dylan L.
Dylan L.

Reputation: 1317

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.

Upvotes: 1

Views: 687

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

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.

Upvotes: 1

Related Questions