2016-07-21 72 views
0

我在具有不同-2状态的同一集合中有多个记录。我想要2-2的每​​一个状态记录。从集合中获取2-2记录

样品采集

[ 
    { 
    "title": "Record1", 
    "status": "pending" 
    }, { 
    "title": "Record2", 
    "status": "ready" 
}, { 
    "title": "Record3", 
    "status": "ready" 
}, { 
    "title": "Record4", 
    "status": "ready" 
}, { 
    "title": "Record5", 
    "status": "pending" 
}, { 
    "title": "Record6", 
    "status": "pending" 
}, { 
    "title": "Record7", 
    "status": "pending" 
}, { 
    "title": "Record8", 
    "status": "pending" 
}, { 
    "title": "Record9", 
    "status": "pending" 
}, { 
    "title": "Record10", 
    "status": "pending" 
}, { 
    "title": "Record11", 
    "status": "ready" 
}] 

预期结果

[ 
    { 
     "title": "Record1", 
     "status": "pending" 
    }, 
    { 
     "title": "Record5", 
     "status": "pending" 
    }, 
    { 
     "title": "Record2", 
     "status": "ready" 
    }, 
    { 
     "title": "Record3", 
     "status": "ready" 
    } 
] 
+0

在你的问题,你能解释一下你的不同-2和2-2是什么意思?什么逻辑产生了预期的结果? –

回答

0

希望这有助于!

db.test.insert(
{ 
record:[{title:"r1",status:"pending"}, 
     {title:"r2",status:"ready"}, 
     {title:"r3",status:"pending"}, 
     {title:"r4",status:"pending"}, 
     {title:"r5",status:"ready"}, 
     {title:"r6",status:"ready"} 
    ] 
} 
) 

db.test.aggregate(
    [ 
     {$unwind:"$record"}, 
     {$group:{_id:"$record.status",titles:{$addToSet:"$record.title"}}}, 
     {$project:{_id:0,status:"$_id",records:{$slice:["$titles",2]}}}, 
     {$unwind:"$records"} 
    ] 
) 

结果:

{ "status" : "pending", "records" : "r1" } 
{ "status" : "pending", "records" : "r3" } 
{ "status" : "ready", "records" : "r5" } 
{ "status" : "ready", "records" : "r2" } 
+0

我使用laravel和我收到错误 MongoResultException在Collection.php线42: 本地主机:27017:异常:无效运算符 '$切片' –

+0

我的代码是 $水库=用户::原始() - >集合体([ \t \t \t [ '$组'=> \t \t [ \t \t \t '_id'=> '$状态', \t \t \t '标题'=> [ '$ addToSet'=>' $ first_name'] \t \t] \t \t], \t \t [ '$项目'=> \t \t \t [ '_id'=> 0, '状态'=> '$ _id', '记录'=> [“$切片'=> ['$ titles',2]]] \t \t], \t \t]); –

+0

你的mongoDB版本是什么? –