我有一堆记录,我需要得到最新的(最近的)和最老的(最近的)。
谷歌搜索时,我发现this topic,我看到了几个问题:
// option 1
Tweet.findOne({}, [], { $orderby : { 'created_at' : -1 } }, function(err, post) {
console.log( post );
});
// option 2
Tweet.find({}, [], {sort:[['arrival',-1]]}, function(err, post) {
console.log( post );
});
不幸的是他们都错了:
TypeError: Invalid select() argument. Must be a string or object.
链接也有这个:
Tweet.find().sort('_id','descending').limit(15).find(function(err, post) {
console.log( post );
});
那一个错误:
TypeError: Invalid sort() argument. Must be a string or object.
那么我该如何获得这些记录呢?
更理想的是,我只想要最旧和最新记录之间的时间差异(秒?),但我不知道如何开始这样的查询。
这是架构:
var Tweet = new Schema({
body: String
, fid: { type: String, index: { unique: true } }
, username: { type: String, index: true }
, userid: Number
, created_at: Date
, source: String
});
我很确定我有最新版本的mongoDB和mongoose。
这就是我根据JohnnyHK提供的答案计算时间跨度的方法:
var calcDays = function( cb ) {
var getOldest = function( cb ) {
Tweet.findOne({}, {}, { sort: { 'created_at' : 1 } }, function(err, post) {
cb( null, post.created_at.getTime() );
});
}
, getNewest = function( cb ) {
Tweet.findOne({}, {}, { sort: { 'created_at' : -1 } }, function(err, post) {
cb( null, post.created_at.getTime() );
});
}
async.parallel({
oldest: getOldest
, newest: getNewest
}
, function( err, results ) {
var days = ( results.newest - results.oldest ) / 1000 / 60 / 60 / 24;
// days = Math.round( days );
cb( null, days );
}
);
}
Mongoose 3.x抱怨[]
调用中的findOne
参数,因为选择要包含的字段的参数不再支持数组格式。
试试这个,找到最新的:
Tweet.findOne({}, {}, { sort: { 'created_at' : -1 } }, function(err, post) {
console.log( post );
});
将-1
更改为1
以找到最老的。
但是因为你没有使用任何字段选择,所以将几个调用链接在一起会更简洁:
Tweet.findOne().sort({created_at: -1}).exec(function(err, post) { ... });
或者甚至将字符串传递给sort
:
Tweet.findOne().sort('-created_at').exec(function(err, post) { ... });
测试了mongoose 5.4.x.
获取10 latest documents
MySchema.find().sort({ _id: -1 }).limit(10)
获取10 oldest documents
MySchema.find().sort({ _id: 1 }).limit(10)
对于版本~3.8 mongoose
找到最后一个条目
model.findOne().sort({ field: 'asc', _id: -1 }).limit(1)
或使用
model.findOne().sort({ field: -_id }).limit(1)
我们有一个叫sort的方法,我们可以得到第一个元素(旧文件),这意味着1对于排序字段或最后一个元素(新文档),这意味着-1对于集合的排序字段。
collectionName.findOne().sort({$natural: -1}).limit(1).exec(function(err, res){
if(err){
console.log(err);
}
else{
console.log(res);
}
}
这将为您提供数据库中记录的最后一个文档。只需遵循相同的概念。