MongoDB匹配数组中的所有元素

时间:2013-08-25 03:31:47

标签: java mongodb mongodb-java

我有一份教育机构文件,如下所示:

{ name: ..., addresses: [...], courses: [ {name: ... , duration: ..., tags[...]} ] }

标签有一个String数组。

我正在尝试找到一个内部有一些标签的课程,例如: java eclipse struts 等...... < / p>

我的搜索方法如下:

public BasicDBList coordinates(List tags){

    BasicDBObject cmdBody = new BasicDBObject("aggregate", "EducationalInstitution");

    List<BasicDBObject> pipeline = new ArrayList<BasicDBObject>();

    BasicDBObject projectParams = new BasicDBObject();
    projectParams.put("name", 1);
    projectParams.put("addresses.state", 1);
    projectParams.put("addresses.locs", 1);
    projectParams.put("courses", 1);


    pipeline.add(new BasicDBObject("$project", projectParams));
    pipeline.add(new BasicDBObject("$match", new BasicDBObject("courses.tags", new BasicDBObject("$all", tags))));
    pipeline.add(new BasicDBObject("$unwind", "$addresses"));

    cmdBody.put("pipeline", pipeline); 

    if( !getDatastore().getDB().command(cmdBody).ok() ){

        throw new MongoException(getDatastore().getDB().command(cmdBody).getErrorMessage());
    }

    return (BasicDBList) getDatastore().getDB().command(cmdBody).get("result");
}

BasicDBObject cmdBody = new BasicDBObject("aggregate", "EducationalInstitution"); List<BasicDBObject> pipeline = new ArrayList<BasicDBObject>(); BasicDBObject projectParams = new BasicDBObject(); projectParams.put("name", 1); projectParams.put("addresses.state", 1); projectParams.put("addresses.locs", 1); projectParams.put("courses", 1); pipeline.add(new BasicDBObject("$project", projectParams)); pipeline.add(new BasicDBObject("$match", new BasicDBObject("courses.tags", new BasicDBObject("$all", tags)))); pipeline.add(new BasicDBObject("$unwind", "$addresses")); cmdBody.put("pipeline", pipeline); if( !getDatastore().getDB().command(cmdBody).ok() ){ throw new MongoException(getDatastore().getDB().command(cmdBody).getErrorMessage()); } return (BasicDBList) getDatastore().getDB().command(cmdBody).get("result"); }

这个实现有2个问题:

1-如果一门课程符合某些参数,此查询将返回所有院校课程。例如,如果我搜索 java 并且该机构有一些Java课程,则所有课程都将返回

2-似乎 $ all 效果不佳。 看起来我的查询正在搜索一些教育机构,在其课程中有这些标签,而不是某些课程里面有那些标签

有人可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

你必须首先解开课程,否则它将被视为一个数组,查询将尝试找到整个文件(机构)而不是列表元素(课程)

pipeline.add(new BasicDBObject("$project", projectParams));
pipeline.add(new BasicDBObject("$unwind", "$courses"));
pipeline.add(new BasicDBObject("$match", new BasicDBObject("courses.tags", new BasicDBObject("$all", tags))));
pipeline.add(new BasicDBObject("$unwind", "$addresses"));