Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取mongodb中disctinct属性类型列表的最后插入_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

获取mongodb中disctinct属性类型列表的最后插入

获取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

我有一张收款单。每个帐户文档有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: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'}}])