mongodb 获取最后插入的文档 [英] mongodb get last inserted document
问题描述
此 Meteor 代码尝试查找集合中的最后一个文档.
This Meteor code tries to find the last document in a collection.
.find({userId: this.userId}, {sort: {createdAt: -1}, limit: 1});
但是由于所有文档都是按时间顺序排列的,我想删除 createdAt 字段,所以一旦它被删除",是否有一种不昂贵"的方法来返回最后输入的文档?谢谢
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) 首先进行排序等等
$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});
});
推荐答案
我将假设昂贵是指执行时间.在这种情况下,您需要 createdAt
字段、createdAt
上的二级索引,并使用 findOne()
语句.要在 createdAt
上为您的集合创建索引,请执行以下操作:
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 });
然后在您的发布中:
Meteor.publish('myCol', function () {
return MyCol.find({userId: this.userId}, { sort: { createdAt: -1 } });
});
这篇关于mongodb 获取最后插入的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!