本文介绍了使用MongoDB Java驱动程序通过查询获取每个文档中的字段数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to get the number of fields in document using a Query From MongoDB java Driver

示例:

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

注意:在第二个文档中,"type1"键不存在.

Note: In second document "type1" key doesnt exist .

当我投影时

是否可以仅投影"type1"和"type2"并获取该文档中现有字段的数量.

Is it possible to project only "type1" and "type2" and get number of fields existing in that document.

使用当前代码,我将获取所有文档并逐一搜索整个光标中是否存在我正在寻找的键:摘录的代码如下:

With current code i am getting all the documents and individually searching if there is the key i am looking is present in the whole cursor:The code snipped is as follows:

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("*********************************************");
    }

}

如果记录较少,则此代码将正常工作.如果每个文档包含500万个文档,则其中有5000000个,则应用程序崩溃,因为每次迭代我们都会涉及更多的垃圾回收正在创建文档.还有其他方法可以实现上述功能吗?

This code is working if the records are less it wont be over load to the application ..Suppose there are 5000000 with each Document containing 120 types , the application is crashing as there would be more garbage collection involved as for every iteration we are creating a document.Is there any other approach through which we can achieve the above stated functionality.

推荐答案

从您的Java代码中我读到

From your java code I read

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

在此假设下,您可以映射减少,如下所示:

With this assumption, you can map-reduce it as following:

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限制.对于较大的响应,您需要对集合进行output,您可以像往常一样查询和迭代该集合.

out:{inline:true} works for small datasets, when result fits into 16Mb limit. For larger responses you need to output to a collection, which you can query and iterate as usual.

这篇关于使用MongoDB Java驱动程序通过查询获取每个文档中的字段数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:03