如何在Mongodb中单独查询数组中的项目

时间:2017-03-13 13:56:49

标签: mongodb

我的收藏名称是员工,我的收藏品如下

{
   "Title":"IssueFixingTeam",
   "TeamLead":"Mr.Bean",
   "workers":["xxx","yyy","zzz"]
 },

{
   "Title":"DevelopmentTeam",
   "TeamLead":"Mr.John Doe",
   "workers":["aa","dd","ss"]
 }

如何查询,TeamLead" Mr.Bean" 提前致谢

3 个答案:

答案 0 :(得分:1)

如果您只对一条记录感兴趣(否则,请参阅@felix的回答)属于" Mr.Bean",那么这可以为您提供所需的数量:

@media (min-device-width: 220px) and (max-device-width: 480px)
{
  /*my styling*/
}

答案 1 :(得分:0)

使用匹配

   to filter TeamLead: Mr.Bean

在Project

中使用Size运算符
   to get size of array,



    db.collection.aggregate([{
        $match: {
            TeamLead: "Mr.Bean"
        }
    }, {
        $project: {
            "TeamLead":1,
            workers: {
                $size: "$workers"
            }
        }
    }])

答案 2 :(得分:0)

您可以使用aggregation framework

如果您只对匹配特定TeamLead和每个文档的 的文档感兴趣:

db.foo.aggregate([{$match: {"TeamLead": "Mr.Bean"}},
                  {$project: {"num_workers": {$size: "$workers"}}}])

输出:

{ "_id" : ObjectId("58c6a5ef9bc86fa5c7e4fa50"), "num_workers" : 3 }

如果您想按TeamLead对文档进行分组,并获取每个TeamLead下的唯一工作人员数量:

db.foo.aggregate([{$group: {"_id": "$TeamLead", "workers": {$addToSet: "$workers"}}},
                  {$unwind: "$workers"},
                  {$project: {"num_workers": {$size: "$workers"}}}])

输出:

{ "_id" : "Mr.John Doe", "num_workers" : 3 }
{ "_id" : "Mr.Bean", "num_workers" : 3 }