【问题标题】:Get the count of Fields in each document through query using MongoDB java driver使用 MongoDB java 驱动程序通过查询获取每个文档中的字段数
【发布时间】:2016-02-06 13:28:27
【问题描述】:

是否可以使用 MongoDB java 驱动程序中的查询来获取文档中的字段数

例子:

 Document1 :{_id:1,"type1": 10 "type2":30,"ABC":123,"DEF":345}
 Document2 :{_id:2,"type2":30,"ABC":123,"DEF":345}

注意:在第二个文档中“type1”键不存在。

当我投影时

是否可以仅投影“type1”和“type2”并获取该文档中存在的字段数。

使用当前代码,我正在获取所有文档并单独搜索我正在寻找的键是否存在于整个光标中: 截取的代码如下:

MongoClient mcl=new MongoClient();
MongoDatabase mdb=mcl.getDatabase("test");
MongoCollection mcol=mdb.getCollection("testcol");
FindIterable<Document> findIterable = mcol.find();
MongoCursor<Document> cursor = findIterable.iterator();
//Here am having 120 types checking if each type is present..
while(cursor.hasNext())
{

Document doc=cursor.next();
int numberOfTypes=0;
for(int i=1;i<=120;i++)
{
if(doc.containsKey("type"+i))
{
numberOfTypes++;
}
}
System.out.println("*********************************************");
System.out.println("_id"+doc.get("_id"));
    System.out.println("Number of Types in this document are "+numberOfTypes);
System.out.println("*********************************************");
    }

}

如果记录较少,此代码将正常工作。假设每个 Document 包含 120 种类型有 5000000 个,应用程序正在崩溃,因为每次迭代都会涉及更多垃圾收集正在创建一个文档。有没有其他方法可以实现上述功能。

【问题讨论】:

    标签: mongodb mongodb-query mongodb-java


    【解决方案1】:

    从我读到的你的 java 代码

    仅投影“type1”和“type2”并获取该文档中存在的字段数。

    作为

    project only type[1..120] fields and number of such fields in the document
    

    有了这个假设,你可以map-reduce它如下:

    db.testcol.mapReduce(
    function(){
        value = {count:0};
        for (i = 1; i <= 120; i++) {
            key = "type" + i
            if (this.hasOwnProperty(key)) {
                value[key] = this[key];
                value.count++
           }
        }
        if (value.count > 0) {
            emit(this._id, value);
        }
    },
    function(){
        //nothing to reduce
    },
    {
        out:{inline:true}
    });
    

    out:{inline:true} 适用于小型数据集,当结果适合 16Mb limit 时。对于较大的响应,您需要 output 到一个集合,您可以像往常一样查询和迭代该集合。

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      相关资源
      最近更新 更多