2016-07-21 79 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版本是什麼? –