本文介绍了计算 MongoDB 集合中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组这样的文档:

{
    "_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 集合中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:22