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

3 Answers 3

2

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

collection.FindOne(ctx, bson.M{"$natural": -1})
Sign up to request clarification or add additional context in comments.

1 Comment

Hi I get unknown top level operator: $natural if I try this. Do you reckon what can it be?
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)

1 Comment

which is faster ?
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)

1 Comment

Tried this, myOptions := options.FindOne() myOptions.SetSort(bson.M{"$natural":-1}) current, err := idCollection.Find(context.TODO(), myOptions) current becomes null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.