从收集中获得2-2的记录

时间:2016-07-21 14:08:49

标签: php mongodb

我在同一个集合中有多条记录,具有不同的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"
    }
]

1 个答案:

答案 0 :(得分: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" }
相关问题