[GODRIVER-2267] Continue run FindOneAndUpdate to get sequence ,but not inc, still the first result Created: 10/Jan/22  Updated: 27/Oct/23  Resolved: 12/Jan/22

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

Type: Bug Priority: Critical - P2
Reporter: oy h 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 inc.go    

 Description   

type Sequence struct

{     Id       primitive.ObjectID `json:"id"   form:"id"  bson:"_id"`     Field    string             `json:"field" form:"field" bson:"field"`     Sequence int64              `json:"sequence" form:"sequence" bson:"sequence"` }

 
func (model *Sequence) GetNextSequence(field string) (int64, error)

{     err := util.C(model).FindOneAndUpdate(context.TODO(),         bson.M\{"field": "Account.Number"}

, bson.M{"$inc": bson.M{"sequence": 1}},
        options.FindOneAndUpdate().SetUpsert(true)).Decode(&model)
    if err != nil

{         return -1, err     }

    return model.Sequence, nil
}
The first run func,can get correct result.Continue to run func  ,but not inc, still the first result. What is the right thing to do?
Thanks。



 Comments   
Comment by Benji Rewis (Inactive) [ 12/Jan/22 ]

No worries. Feel free to comment on this ticket or open another if you have another issue.

Comment by oy h [ 12/Jan/22 ]

Sorry, I didn't turn off the vscode test cache. FindOneAndUpdate is right。Thanks for your help。

Comment by Benji Rewis (Inactive) [ 11/Jan/22 ]

Hello again, 8080268@qq.com! I believe what you're saying is that it's surprising that when you run FindOneAndUpdate with a $inc stage, the returned document does not show the increment that has been executed. By default, FindOneAndUpdate will return the document it found before it has been potentially updated. You'd have to use SetReturnDocument with a value of options.After to specify that you'd like the updated document to be the one returned. I've attached some example code similar to the code you've provided that shows how you might do so. Let me know if this is helpful.

inc.go

Comment by Benji Rewis (Inactive) [ 10/Jan/22 ]

Hello 8080268@qq.com! Thanks for your bug report; we're taking a look now.

Comment by oy h [ 10/Jan/22 ]

If drop Sequence collection ,then run func, return err "Get failed mongo: no documents in result ".

But db had document.

{\{ "_id" : ObjectId("61dbb4cd3da10a3250f8a75f"), "field" : "Account.Number", "sequence" : 1}
Generated at Thu Feb 08 08:38:12 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.