Get last inserted element from mongodb in GoLang using FindOne and $natural

Viewed 754

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 Answers

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)
Related