3

I'm trying to retrieve the last inserted document using FindOne as suggested elsewhere:

collection.FindOne(ctx, bson.M{"$natural": -1})

Get last inserted element from mongodb in GoLang

Here is my example:

    var lastrecord bson.M
if err = collection.FindOne(ctx, bson.M{"$natural": -1}).Decode(&lastrecord); err != nil {
    log.Fatal(err)
}
fmt.Println(lastrecord)

Unfortunately I get the following error:

(BadValue) unknown top level operator: $natural

I'd prefer to use FindOne if possible.

1 Answer 1

2

You want to sort using natural order, yet you specify it as a filter, which is what the error says.

To use $natural to specify sorting:

opts := options.FindOne().SetSort(bson.M{"$natural": -1})
var lastrecord bson.M
if err = coll.FindOne(ctx, bson.M{}, opts).Decode(&lastrecord); err != nil {
    log.Fatal(err)
}
fmt.Println(lastrecord)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - I knew there was an additional item I was missing but didn't know how to apply the sort to find one. Are you able to point me at some useful docs on how to construct the opts?
Options is a builder, it has methods to set any option. Check out the docs of course: godoc.org/go.mongodb.org/mongo-driver/mongo/options

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.