获取每个子集的最新对象
Get newest object of each subset
我正在开发基于 mongodb and mongoose 的应用程序。我的模式之一具有以下形式:
var schema = new mongoose.Schema(
{
name: { type: String },
timestamp: { type: Number, default: Date.now },
// further properties
});
schema.index({ name: 1, timestamp: -1 });
我想检索一组 name
字符串的最新对象(即最大的 timestamp
)。
例如,考虑一组名称 ['a','b']
。如何查询数据库,以便返回一个对象集合,其中包含最新条目 id=='a'
和最新条目 id=='b'
?
[更新:这个想法是为了避免多次查询数据库(即每个名称一次)。]
"How do I query the database such that I get returned a collection of objects that contains the newest where id=='a'"
db.collection.find({ name : 'a' }).sort({ timestamp : -1 })
"and the newest entry where id=='b'?"
db.collection.find({ name : 'b' }).sort({ timestamp : -1 }).limit(1)
我正在开发基于 mongodb and mongoose 的应用程序。我的模式之一具有以下形式:
var schema = new mongoose.Schema(
{
name: { type: String },
timestamp: { type: Number, default: Date.now },
// further properties
});
schema.index({ name: 1, timestamp: -1 });
我想检索一组 name
字符串的最新对象(即最大的 timestamp
)。
例如,考虑一组名称 ['a','b']
。如何查询数据库,以便返回一个对象集合,其中包含最新条目 id=='a'
和最新条目 id=='b'
?
[更新:这个想法是为了避免多次查询数据库(即每个名称一次)。]
"How do I query the database such that I get returned a collection of objects that contains the newest where id=='a'"
db.collection.find({ name : 'a' }).sort({ timestamp : -1 })
"and the newest entry where id=='b'?"
db.collection.find({ name : 'b' }).sort({ timestamp : -1 }).limit(1)