I
I
Ivan2021-01-21 14:58:42
MongoDB
Ivan, 2021-01-21 14:58:42

Why doesn't FindOneAndUpdate() work using mongo driver?

Hello. It is necessary to update the document, but if there is no such document according to the specified criteria, create it. But provided that the document exists - return its version before the update. Here's how I'm trying to do it but I'm getting the error no documents in result . Can you please tell me what is wrong here?

PS If you put the After option in the ReturnDocument, then everything works. But I need to return the document before the update

upsert := true
before := options.Before
opt := options.FindOneAndUpdateOptions{
    Upsert: &upsert,
                ReturnDocument: &before,
  }
result := collectionEvent.FindOneAndUpdate(ctx, filter, update, &opt)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Shalganov, 2021-02-22
@Aco

I recommend using a factory for options

options.FindOneAndUpdate().SetReturnDocument(options.Before).SetUpsert(true)

On the issue, most likely there is no document and the truth is on the filter. Check the condition and drop the filter here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question