Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a field and a count of a nested array in mongodb [duplicate]

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
} 
like image 792
Nimphadora Avatar asked Apr 30 '17 10:04

Nimphadora


People also ask

How do I query a nested object in MongoDB?

Query on Nested Field To specify a query condition on fields in an embedded/nested document, use dot notation ( "field. nestedField" ). When querying using dot notation, the field and nested field must be inside quotation marks.

How do I count multiple fields in MongoDB?

In MongoDB, when we have a large dataset inside the collection and we want to count where the field value is repeating on multiple fields then we use $group aggregation. Example: Here, we are taking an example in which we apply $group aggregation with multiple fields and get the count of duplicate field values.

How do I count fields in MongoDB?

First stage $project is to turn all keys into array to count fields. Second stage $group is to sum the number of keys/fields in the collection, also the number of documents processed. Third stage $project is subtracting the total number of fields with the total number of documents (As you don't want to count for _id ).


1 Answers

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

db.collection.aggregate( { $project: {name:1, telephoneCount: {$size: "$telephone"}}})
like image 90
s7vr Avatar answered Sep 18 '22 17:09

s7vr