Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

count - Get number of documents per field in MongoDB, like Studio3T Schema operation

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??

question from:https://stackoverflow.com/questions/65944571/get-number-of-documents-per-field-in-mongodb-like-studio3t-schema-operation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...