Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb get last inserted document

Tags:

mongodb

meteor

This Meteor code tries to find the last document in a collection.

.find({userId: this.userId}, {sort: {createdAt: -1}, limit: 1});

But since all the documents are in chronological order, I thought to remove the createdAt field, so once that is 'deleted', Is there a "not expensive" way to return just the last entered document? Thanks

{userId: 'someId', info: 'someInfo'}
myCol.findLast().info;              <--- my wish list

$last(aggregation) in the docs first does sorting among other things

edit
An attempt to utilise the idea given by Stephen Woods;

server.js

MyCol._ensureIndex({createdAt: -1});
MyCol.before.insert(function (userId, doc) {
  doc.userId = userId;
  createdAt = Date.now();
});
Meteor.publish('myCol', function () {
  return MyCol.findOne({userId: this.userId});
});
like image 566
Fred J. Avatar asked Jun 24 '26 10:06

Fred J.


1 Answers

I'm going to make the assumption that by expensive you mean execution time. In that case, you want a createdAt field, a secondary index on createdAt, and to use a findOne() statement. To create the index on createdAt for your collection, do:

myCol._ensureIndex({ createdAt: -1 });

Then in your publish:

Meteor.publish('myCol', function () {
  return MyCol.find({userId: this.userId}, { sort: { createdAt: -1 } });
});
like image 170
Stephen Woods Avatar answered Jun 26 '26 06:06

Stephen Woods



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!