1

How do I obtain the distribution of fields among a MongoDB collection, i.e the total count of documents for each field (without knowing the fields) ?

E.g. considering these documents :

{ "doc": { "a": …, "b": … } }
{ "doc": { "a": …, "c": … } }
{ "doc": { "a": …, "c": …, "d": { "e": … } } }

I would like to get

{ "a": 3, "b": 1, "c": 2, "d": 1, "d.e": 1 }

Studio3T has a "Schema" feature which does exactly that (and a bit more) for a random sample of the DB, how is the query constructed ?

Skippy le Grand Gourou
  • 6,976
  • 4
  • 60
  • 76

1 Answers1

0

One way is to use db.collection.countDocuments() with the $exists operator:

db.collection.countDocuments({ a: { $exists: true});
db.collection.countDocuments({ b: { $exists: true});
db.collection.countDocuments({ c: { $exists: true});
Marcus Castanho
  • 145
  • 1
  • 3
  • 9
  • 1
    Thanks for the effort, but this solution is very inefficient. Furthermore, it's impracticable when you don't know the fields in advance (I'll add this point in the question). – Skippy le Grand Gourou Jan 29 '21 at 07:45