[GODRIVER-2230] Upsert in findOneAndUpdate not work Created: 15/Nov/21  Updated: 27/Oct/23  Resolved: 17/Nov/21

Status: Closed
Project: Go Driver
Component/s: None
Affects Version/s: 1.7.4
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Tung Nguyen Assignee: Benji Rewis (Inactive)
Resolution: Gone away Votes: 0
Labels: Bug
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: File returndocumentexample.go    
Documentation Changes: Not Needed

 Description   

MogoDB version: 5.0.3

Driver version: v1.7.4

Code:
type mongoCounter struct {
Type string `bson:"type"`
Sequence int `bson:"sequence"`
}
result := mongoCounter{}
err = db.Collection("counters").FindOneAndUpdate(context.Background(), bson.M{
"type": "non_existen_type",
}, bson.M{
"$inc": bson.M{
"sequence": 1,
},
}, options.FindOneAndUpdate().SetUpsert(true)).Decode(&result)
fmt.Println(err)
 

 

 

Result:

 

mongo: no documents in result

 

Expected:

The document should be created and err is nil.



 Comments   
Comment by Benji Rewis (Inactive) [ 17/Nov/21 ]

Great! And happy to help. Feel free to comment on this ticket/open a new one if anything else comes up.

Comment by Tung Nguyen [ 17/Nov/21 ]

Hi @Benji Rewis,

Thank you for provided example and clear explained, it worked with SetReturnDocument to options.After

Sorry for fall alert, please help me close this ticket.

Comment by Benji Rewis (Inactive) [ 16/Nov/21 ]

Hello again, oxycoder@gmail.com!

If you’d like the new, upserted document to be returned from the call to FindOneAndUpdate, you’ll have to set the ReturnDocument value on your FindOneAndUpdate options.

Setting Upsert (see the server documentation on the upsert field here) to true means that if FindOneAndUpdate does not find a document matching your provided filter, a document identical to the filter will be inserted to the specified collection. FindOneAndUpdate will still return null after the insertion unless you also specify ReturnDocument as true. In the Go driver, you can do this with the SetReturnDocument function and the options.After constant. I’ve attached some example code to this ticket.

Let me know if that helps.

returndocumentexample.go

Comment by Benji Rewis (Inactive) [ 16/Nov/21 ]

Thanks for your bug report oxycoder@gmail.com! We're investigating this now.

Generated at Thu Feb 08 08:38:07 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.