mongodb - 在带有 mgo 驱动程序的 Upsert 上使用 $setOnInsert
问题描述
您如何使用Go MongoDB 驱动程序的$setOnInsert
任何Upsert
变体?mgo
解决方案
给定任意类型Foo
:
type Foo struct {
ID bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
Bar string `json:"bar" bson:"bar"`
Created *time.Time `json:"created,omitempty" bson:"created,omitempty"`
Modified *time.Time `json:"modified,omitempty" bson:"modified,omitempty"`
}
还有Upsert
选择器,它决定了这是一个Update
还是一个Insert
:
selector := bson.M{
"bar": "bar",
}
仅当正在插入文档时才插入创建日期的Upsert
查询将如下所示(其中now
是 type 的变量time.Time
):
query := bson.M{
"$setOnInsert": bson.M{
"created": &now,
},
"$set": Foo{
Bar: "bar",
Modified: &now,
},
}
将所有这些定义的类型和变量与globalsign/mgo
驱动程序一起使用,整个查询由以下代码执行:
if _, err := session.DB("test").C("test").Upsert(selector, query); err != nil {
// Handle error
}
推荐阅读
- python - 如何从python中的str中删除字符?
- ruby-on-rails - 升级到 Rails 5 后,我在尝试登录时收到无效的 CSRF 令牌错误
- agda - 抽象呼叫站点后终止检查器失败
- machine-learning - 什么是 N-gram?
- selenium - 如何在 selenium 中为该网站“https://www.goibibo.com/”处理“来自”和“目的地”框中的自动建议
- ruby-on-rails - NoMethodError:Devise:Module 的未定义方法“设置”
- java - Java在数组中获取0的值
- networking - 网络托管公司如何能够为每个人提供公共 IPv4 地址
- bash - 在tail命令中使用变量
- java - 如何使用 WebFilter 实现授权头检查