简体   繁体   中英

(MongoDB / Mongoose) Increment a value in an array of objects

I have a document that looks like this:

{
  "id": "12345",
  "channels": [
    {
      "id": "67890",
      "count": 1
    }
  ]
}

What I want to do is increment a given channel count by one. So a user sends a message and I look up the user, find the proper channel by "id" in the "channels" array, and increment "count" by one.

I tried the following query:

UserModel.findOneAndUpdate({id: this.id}, 
  {'channels.id': channel.id}, 
  {$set: {$inc: {'channels.$.count': 1}}}

It didn't fail, surprisingly. But it also didn't increment the count.

Two fixes needed: query has to be a single object and $inc is a separate operator so you don't need $set :

UserModel.findOneAndUpdate({id: this.id, 'channels.id': channel.id},
    { $inc: {'channels.$.count': 1}})

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