【问题标题】:Golang MongoDB Increment Integer ValueGolang MongoDB 增量整数值
【发布时间】:2020-07-15 09:21:19
【问题描述】:

我正在使用这个官方库

https://github.com/mongodb/mongo-go-driver

这是我在 MongoDB 中的一份文档

{
    "_id": "5f0ebe6dfcee0f34c64b23b0",
    "userID": "user A",
    "unread": 1,
    "projectID": 2
}

问题是我想增加(也可能减少)“未读”字段

我尝试过使用“$inc”,结果变成了这样

{
    "_id": "5f0ebe6dfcee0f34c64b23b0",
    "userID": "user A",
    "unread": {
        "$incr": 1,
    },
    "projectID": 2
}

我认为有两个条件

  1. 文档已存在
  2. 文档尚不存在

如果我使用的是UpdateOneUpdateMany,如果文档尚不存在,这将再次成为问题

能帮我解决这个问题的人将不胜感激

谢谢你,干杯^^

【问题讨论】:

  • 请说明您想要实现的目标,并包含您尝试过的代码。使用UpdateOneUpdateMany 是两种不同的情况。您很可能不想在使用 UpdateMany 时插入不存在的文档。
  • 很高兴知道您要实现什么用例。这有助于其他人参考这个问题

标签: mongodb go


【解决方案1】:

我已经得到了答案。所以我做了这样的代码

_, err = m.db.Collection("inbox_counter").UpdateOne(ctx, bson.M{
    "userID":    v.UserID,
    "projectID": v.ProjectID,
}, bson.D{
    {"$inc", bson.D{{"unread", 1}}},
}, options.Update().SetUpsert(true))
if err != nil {
    log.Println(err)
    return err
}

我正在使用 UpdateOne,因为每个用户和项目 ID 只有一个文档

您可以使用运算符$inc 来增加值

感谢@Gibbs 推荐我使用upsert

【讨论】:

    【解决方案2】:

    你必须使用upsert - 如果它存在,它将更新,否则插入。

    Refer this

    db.collectionName.update(
       { item: "ZZZ135" },   // Find query 
       {
         "$set":{                     // Update document
          item: "ZZZ135",
          stock: 5,
          tags: [ "database" ]
         }
       },
       { upsert: true }      // Option
    )
    

    【讨论】:

      【解决方案3】:
      db.getCollection('table_name').update(
         { "key": "value" },   // Find query 
         {
           "$set":{                     // Update document
               "key": value
           },
          "$setOnInsert":{                     // Addd on Insert only
               "key1": value
           },
           "$inc": {
               "numberKey": 1 // Increment unread Or To decrement use -1
            }
         },
         { upsert: true } 
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-19
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        • 2013-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多