英文:
Golang Mongodb $push and if doesn't exist create
问题
所以基本上我有这个结构体,它需要出现在MongoDB中,我需要编写一个查询,首先检查是否已经存在具有profileID的对象,如果存在,则将新的offer id推送到现有对象的offers数组中。如果不存在具有profileID的对象,则创建一个并将offer id添加到offers数组中。是否可以在一次查询中完成?如果可以,有人可以帮我实现吗?
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
}
英文:
So basically I have this struct that has to appear in mongoDb and I have to write a query witch would firstly check if an object with the profileID already exists it would push a new offer id to the existing objects offers array. And if an Object with the profileID does not exist it would create one and add the offer id to the offers array. Is it possible to do it in one query? if so could anyone help me on how it could be implemented?
type IgnoreOffer struct {
ProfileID primitive.ObjectID `json:"profileID" bson:"profileID"`
Offers []primitive.ObjectID `json:"offers,omitempty" bson:"offers,omitempty"`
}
Here's my code for however it does not create a new object in the database.
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
}
答案1
得分: 1
你的情况需要使用 upsert 操作:
_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
英文:
You need an upsert in your case:
_, err := getIgnoreOffersCollection().UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论