Golang upsert with $inc issue

Hi,

I’m just getting started with golang and MongoDB and have run into a bit of a issue with upserting using $inc to increment a value in the document. The code I’m using is…

_, err = s.Collection.UpdateOne(ctx, bson.M{
	"month":    primitive.NewDateTimeFromTime(GetFirstOFMonth()),
	"projectId": projId,
}, bson.D{
	{Key: "$inc", Value: bson.D{{Key: "count", Value: 1}}},
}, options.Update().SetUpsert(true))
if err != nil {
	log.Println(err)
}

So if there is a document for this month I want it to increment the count field and if no document exists for the month it will create a new document. The insert part works fine but the update doesn’t increment the count field. If I change the value of the count increment is seemt to work on the first run but not subsequent ones. Anyone know what I’m doing wrong?

Hi :wave: @James_Cooke,

Welcome to the MongoDB community forums :sparkles:

I suspect your update operation is not finding any documents to update on subsequent runs, which is why the count field is not being incremented. This could be because the query filter you’re using is not matching the documents you expect.

I tried the same code mentioned above by passing the value of projectId and it worked fine. Sharing the code for reference:

	// Upsert document with $inc
	projId, _ := primitive.ObjectIDFromHex("63eefe67ef2f5959294bc653")
	_, err = collection.UpdateOne(ctx, bson.M{
		"month":     primitive.NewDateTimeFromTime(GetFirstOFMonth()),
		"projectId": projId,
	}, bson.D{
		{Key: "$inc", Value: bson.D{{Key: "count", Value: 1}}},
	}, options.Update().SetUpsert(true))
	if err != nil {
		log.Println(err)
	}

The code returned the following output, and it’s working as expected:

➜ go run update.go
2023/02/17 09:48:05 map[_id:ObjectID("63eefe6728f1bf90d6ad7b16") count:2 month:1675189800000 projectId:ObjectID("63eefe67ef2f5959294bc653")]
➜ go run update.go
2023/02/17 09:48:09 map[_id:ObjectID("63eefe6728f1bf90d6ad7b16") count:3 month:1675189800000 projectId:ObjectID("63eefe67ef2f5959294bc653")]

If this is not the result you’re seeing, could you please provide some example documents and more details on the output you’re seeing? It will be helpful to narrow down the specific issues.

Let me know if you have any further questions.

Best,
Kushagra