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.

icza
  • 389,944
  • 63
  • 907
  • 827
Ironkaiju
  • 21
  • 2

1 Answers1

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)
icza
  • 389,944
  • 63
  • 907
  • 827
  • 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 '21 at 09:32
  • Options is a builder, it has methods to set any option. Check out the docs of course: https://godoc.org/go.mongodb.org/mongo-driver/mongo/options – icza Jan 14 '21 at 09:44