获取mongodb中disctinct属性类型列表的最后插入
我有一张收款单。每个帐户文档有3个属性_id、类型、年龄;有3种不同的类型:男性、女性和其他。任何单个文档将只包含其中一种类型获取mongodb中disctinct属性类型列表的最后插入,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有一张收款单。每个帐户文档有3个属性_id、类型、年龄;有3种不同的类型:男性、女性和其他。任何单个文档将只包含其中一种类型 { _id:ObjectId(xxxxx1), type:"Male", age:20 } { _id:ObjectId(xxxxx2), type:"Female", age:20 } { _id:ObjectId(xxxxx3), type:"Male", age:21 } { _id:ObjectId(xxxxx4), type:"Other", age:3
{
_id:ObjectId(xxxxx1),
type:"Male",
age:20
}
{
_id:ObjectId(xxxxx2),
type:"Female",
age:20
}
{
_id:ObjectId(xxxxx3),
type:"Male",
age:21
}
{
_id:ObjectId(xxxxx4),
type:"Other",
age:30
}
{
_id:ObjectId(xxxxx5),
type:"Female",
age:31
}
我的问题是,我想提取三种类型中最后插入的文档:
结果将是3个文件
{
_id:ObjectId(xxxxx3), <--- last insert of the Male type
type:"Male",
age:21
}
{
_id:ObjectId(xxxxx4), <--- last insert of the Other type
type:"Other",
age:30
}
{
_id:ObjectId(xxxxx5), <--- last insert of the Female type
type:"Female",
age:31
}
{
_id:ObjectId(XXXXX 3),您需要使用MongoDB的:
测试:
说明:
总之,$group
stage将根据条件\u id:“$type”
对所有匹配的文档进行分组,因此所有具有相同类型的文档将被分组在一起&使用$last
我们将在分组过程中获得最后一个文档
使用replaceRoot
我们将lastDoc
对象作为文档的新根
太棒了!
db.Account.aggregate([
{$group : {_id : '$type', lastDoc : {$last : '$$ROOT'}}},
{$replaceRoot : {newRoot : '$lastDoc'}}])