2

My collection name is employee and my collections as follows

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

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

how to query to find, how many workers are there under TeamLead "Mr.Bean" Thanks in advance

1
  • 1
    share us what have you tried Commented Mar 13, 2017 at 14:04

3 Answers 3

1

if you are interested in just one record (otherwise, see the answer by @felix) belonging to "Mr.Bean", then this could give you the required count:

db.employee.findOne({'TeamLead': 'Mr.Bean'}).workers.length
Sign up to request clarification or add additional context in comments.

Comments

0

Use Match

   to filter TeamLead: Mr.Bean

use Size operator in Project

   to get size of array,



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

Comments

0

You can use the aggregation framework.

In case you are only interested in matching documents of a specific TeamLead and sum per document:

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

Output:

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

If you want to group documents by TeamLead and get the number of unique workers under each TeamLead:

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

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.