2

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)
2
  • 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?
    – Ironkaiju
    Jan 14, 2021 at 9:32
  • 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
    – icza
    Jan 14, 2021 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.