Golang中如何使用MongoDB在不存在情况下执行$push操作
时间:2024-02-25
浏览:279
作者:佚名
有志者,事竟成!如果你在学习Golang,那么本文《Golang中如何使用MongoDB在不存在情况下执行$push操作》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
所以基本上我有这个必须出现在 mongodb 中的结构,我必须编写一个查询,首先检查具有 profileid 的对象是否已经存在,然后将新的优惠 id 推送到现有对象优惠数组中。如果具有 profileid 的对象不存在,它将创建一个对象并将优惠 id 添加到优惠数组中。是否可以在一个查询中完成它?如果是这样,有人可以帮助我如何实施吗?
type ignoreoffer struct {
profileid primitive.objectid `json:"profileid" bson:"profileid"`
offers []primitive.objectid `json:"offers,omitempty" bson:"offers,omitempty"`
}
这是我的代码,但它不会在数据库中创建新对象。
func getIgnoreOffersCollection() *mongo.Collection {
return db.GetMongoCollection("ignoreOffers")
}
func ignoreOffer(profileId primitive.ObjectID, offerId primitive.ObjectID) error {
var offer IgnoreOffer
offer.ProfileID = profileId
ctx, _ := db.GetTimeoutContext()
filter := bson.M{"profileID": profileId}
update := bson.M{
"$set": bson.M{
"updatedAt": time.Now(),
},
"$push": bson.M{
"offers": offerId,
},
}
_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update)
if err != nil {
log.Error("could not update ignoreOffer collection, err: ", err)
return err
}
return nil
}正确答案
您的案例需要更新插入:
_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
热门专题
