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
}
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.
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.
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 ).
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"}}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With