Fred J.
Fred J.

Reputation: 6019

mongodb get last inserted document

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});
});

Upvotes: 3

Views: 3796

Answers (1)

Stephen Woods
Stephen Woods

Reputation: 4049

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 } });
});

Upvotes: 2

Related Questions