Posts tagged "mongodb"

Get distinct field names of sub documents in MongoDB

Published on
#mongodb 

Let's say you have these documents in your collection items:

Aggregations with sub-documents in MongoDB

Published on
#mongodb 

I would like to extract statistics about sub-documents in a collection.

E.g. in the form of count, sum and average for each field

Let's say you have the following documents in the items collection:

db.items.find()
{ "_id" : ObjectId("5f034ce90b15686f5d78baed"), "subDocument" : { "field1" : 42, "field3" : 10 } }
{ "_id" : ObjectId("5f034ce90b15686f5d78baee"), "subDocument" : { "field2" : 14, "field3" : 6 } }
{ "_id" : ObjectId("5f034ce90b15686f5d78baef"), "subDocument" : { "field1" : 6, "field4" : 11 } }
{ "_id" : ObjectId("5f034cea0b15686f5d78baf0"), "subDocument" : { "field3" : 3, "field4" : 26 } }

How would you solve the use-case of aggregating each field of the subDocument's dynamically?

Event without actually "knowing" which fields are contained in subDocument?

Join other 100+ developers!
Consider subscribing if you are into topics like DIY, Node.js, Elixir and more.

View the past editions of my newsletter