2016-03-21 19 views
3

我有以下格式的集合:

{ 
    "_id": 123, 
    "items": [{ 
     "status" : "inactive", 
     "created" : ISODate("2016-03-16T10:39:28.321Z") 
    }, 
    { 
     "status" : "active", 
     "created" : ISODate("2016-03-16T10:39:28.321Z") 
    }, 
    { 
     "status" : "active", 
     "created" : ISODate("2016-03-16T10:39:28.321Z") 
    } 
    ], 
    "status" : "active" 
} 

我想在状态查询的项目,使得与地位对象“主动”数组中仅返回,在查询中也只返回最后2个。

目前我使用$过滤此操作,但我不能够使用$切片$过滤(我认为这是需要什么,我的愿望)一起。下面是我查询的外观现在:

db.collection('collection').aggregate([ 
{$match: {'status': 'active'}}, 
{ 
    $project: { 
     'items': { 
      $filter: { 
       input: '$items', 
       as: 'item', 
       cond: {$eq: ['$$item.status', 'active'] 
      } 
     } 
    } 
}]); 

什么我得到现在的问题是正确的结果,它只是它返回的所有对象的项目场,我只是想最后2个对象。

回答

9

要获得最后两个元素,请使用$slice运算符,并将position操作数设置为-2。当然slice操作符的第一个操作数是$filter表达式,它解析为一个数组。

db.collection.aggregate([ 
    { "$match": { "items.status": "active" } }, 
    { "$project": { 
     "items": { 
      "$slice": [ 
       { "$filter": { 
        "input": "$items", 
        "as": "item", 
        "cond": { "$eq": [ "$$item.status", "active" ] } 
       }}, 
       -2 
      ] 
     } 
    }} 
]) 
+0

太棒了!谢谢 ;) – HVT7