Golang Mongodb $push 和如果不存在则创建

huangapple go评论91阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2022年2月26日 01:53:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/71269875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定