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
} 
0

1 Answer 1

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' },
                },
            }
]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.