查找具有特定匹配数组的文档

时间:2015-02-22 14:46:22

标签: mongodb aggregation-framework

我已经搜索过高低,但却找不到我要找的东西,所以如果已经被问到这么道歉。

考虑以下文件

{
    _id: 1,
    items: [
        {        
            category: "A"
        },
        {        
            category: "A"
        },
        {        
            category: "B"
        },
        {        
            category: "C"
        }]
},
{
    _id: 2,
    items: [
        {        
            category: "A"
        },
        {        
            category: "B"
        }]
},
{
    _id: 3,
    items: [
        {        
            category: "A"
        },
        {        
            category: "A"
        },
        {        
            category: "A"
        }]
}

我希望能够找到那些在items数组中有超过1个“A”类项目的文档。所以这应该找到文件1和3。

这可能吗?

1 个答案:

答案 0 :(得分:1)

使用aggregation

> db.spam.aggregate([
    {$unwind: "$items"}, 
    {$match: {"items.category" :"A"}}, 
    {$group: {
        _id: "$_id", 
        item: {$push: "$items.category"}, count: {$sum: 1}}
    }, 
    {$match: {count: {$gt: 1}}}
])

<强>输出

{ "_id" : 3, "item" : [ "A", "A", "A" ], "count" : 3 }
{ "_id" : 1, "item" : [ "A", "A" ], "count" : 2 }