仅当值大于0时才$ inc(Node.js mongodb)

时间:2019-10-16 13:06:03

标签: node.js mongodb

你好,我有以下更新查询

this.dbService.getCollection(DBCollections.CHANNEL)
  .updateMany(
    {
      'members.skipRounds': { $exists: true },
      _id: channelId,
    },
    { $inc: { 'members.$[].skipRounds': -1 } },
  ).catch(err => console.log(err));

如果当前值大于0,如何仅使skipRounds的值减小-1?

这是我的频道收藏的样子

Channels [
{
  _id:1
  users:[
  {
    _id:1
    skipRounds:1
  },
  {
    _id:2
    skipRounds:3
  },       
  ]
},
{
  _id:2
  users:[
  {
    _id:1
    skipRounds:3
  },
  {
    _id:2
    skipRounds:5
  },       
  ]
},   
] 

1 个答案:

答案 0 :(得分:0)

请选中此选项可能会对您有所帮助。

    this.dbService.getCollection(DBCollections.CHANNEL).updateMany(
    {
      'users.skipRounds': { $exists: true },
    },
    { $inc: { 'users.$[element].skipRounds': -1 } },
    { arrayFilters: [ { "element.skipRounds": { $gt: 0 } } ]}
).catch(err => console.log(err));