mp3por
mp3por

Reputation: 1852

Get last inserted element from mongodb in GoLang

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

Upvotes: 0

Views: 4188

Answers (3)

mama
mama

Reputation: 2227

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)

Upvotes: 0

blacha
blacha

Reputation: 151

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

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

Upvotes: 2

Benjamin Kadish
Benjamin Kadish

Reputation: 1500

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)

Upvotes: 1

Related Questions