我正在使用这个官方图书馆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
}
我认为会有两个条件如果我使用的是
UpdateOne
或UpdateMany
,如果该文档尚不存在,将再次成为问题有人可以帮助我
谢谢,干杯^^
最佳答案
您必须使用upsert
-如果存在,它将进行更新,否则会插入。
Refer this
db.collectionName.update(
{ item: "ZZZ135" }, // Find query
{
"$set":{ // Update document
item: "ZZZ135",
stock: 5,
tags: [ "database" ]
}
},
{ upsert: true } // Option
)
关于mongodb - Golang MongoDB增量整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62911602/