0

I have a struct like this:

type SavedData struct {
    ID   bson.ObjectId `bson:"_id"`
    Data string
    Date time.Time
}

I also have my

collection := database.C("coll_name")

How do I retrieve the last inserted entry in this collection ?

Thank you

mp3por
  • 1,796
  • 3
  • 23
  • 35

3 Answers3

2

The accepted answer is 5 years old. This should work Today with mongodb driver

collection.FindOne(ctx, bson.M{"$natural": -1})
blacha
  • 93
  • 2
  • 7
  • 1
    Hi I get `unknown top level operator: $natural` if I try this. Do you reckon what can it be? – mama Feb 25 '21 at 21:07
1

Apparently mongoDB is by default sorted by insertion time according to this question so you can just skip the first N elements of the collection like so.

var myData SavedData 
dbSize, err := collection.Count()
if err != nil {
        return err
}

err = c.Find(nil).skip(dbSize-1).One(&myData)
if err != nil {
        return err
}

or you can search in the reverse order

c.Find(bson.M{ "$natural": -1 }).One(&myData)
Community
  • 1
  • 1
Benjamin Kadish
  • 1,472
  • 11
  • 20
0

You have to use options with mongo-driver if you want to get the latest document in the collection

import(
    ...
    "go.mongodb.org/mongo-driver/mongo/options"
)

myOptions := options.FindOne()
myOptions.SetSort(bson.M{"$natural":-1})
collection.FindOne(ctx, bson.M{}, myOptions)
mama
  • 2,046
  • 1
  • 7
  • 24
  • Tried this, myOptions := options.FindOne() myOptions.SetSort(bson.M{"$natural":-1}) current, err := idCollection.Find(context.TODO(), myOptions) current becomes null – codemonkey Nov 07 '21 at 08:55