10

I have the following mongo db collection

{
 "_id" : 1,
 "name" : "Sam",
 "telephone" : [1234,4567,8678],
 "age" : 34
},
{
 "_id" : 2,
 "name" : "Joe",
 "telephone" : [4456,4434],
 "age" : 42
}

I want to fetch the name and the count of telephone. what should be the query? My output should be as below.

{
  "name" : "Sam",
  "telephoneCount" : 3
},
{
  "name" : "Joe",
  "telephoneCount" : 2
} 
s7vr
  • 73,656
  • 11
  • 106
  • 127
Nimphadora
  • 113
  • 2
  • 10

1 Answers1

17

You can use the below query. Use $project to keep the name field and $size to count the telephone numbers.

db.collection.aggregate([
{
                $project: {
                    name: name,
                    telephoneCount: { $size: '$telephone' },
                },
            }
]);
s7vr
  • 73,656
  • 11
  • 106
  • 127