问题描述
我有一个像这样的文件集:
I have a collection of documents like this one:
{
"_id" : ObjectId("..."),
"field1": "some string",
"field2": "another string",
"field3": 123
}
我希望能够遍历整个集合,并找到其中的全部字段.在此示例文档中,有3个(我不想包含_id),但是在文档中它的范围是2到50个字段.最终,我只是在寻找每个文档的平均字段数.
I'd like to be able to iterate over the entire collection, and find the entire number of fields there are. In this example document there are 3 (I don't want to include _id), but it ranges from 2 to 50 fields in a document. Ultimately, I'm just looking for the average number of fields per document.
有什么想法吗?
推荐答案
PRIMARY> var count = 0;
PRIMARY> db.my_table.find().forEach( function(d) { for(f in d) { count++; } });
PRIMARY> count
1074942
这是我弄清楚如何执行此操作的最简单方法.在非常大的数据集上,走Map-Reduce路径可能很有意义.但是,虽然您的设备足够小,但是可以.
This is the most simple way I could figure out how to do this. On really large datasets, it probably makes sense to go the Map-Reduce path. But, while your set is small enough, this'll do.
这是O(n^2)
,但我不确定是否有更好的方法.
This is O(n^2)
, but I'm not sure there is a better way.
这篇关于计算MongoDB集合中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!