Example usage for com.mongodb.client.model Projections include

List of usage examples for com.mongodb.client.model Projections include

Introduction

In this page you can find the example usage for com.mongodb.client.model Projections include.

Prototype

public static Bson include(final List<String> fieldNames) 

Source Link

Document

Creates a projection that includes all of the given fields.

Usage

From source file:org.opencb.commons.datastore.mongodb.MongoDBQueryUtils.java

License:Apache License

public static List<Bson> createGroupBy(Bson query, List<String> groupByField, String idField, boolean count) {
    if (groupByField == null || groupByField.isEmpty()) {
        return new ArrayList<>();
    }/*  ww  w. j  a  v  a  2 s .c o m*/

    if (groupByField.size() == 1) {
        // if only one field then we call to simple createGroupBy
        return createGroupBy(query, groupByField.get(0), idField, count);
    } else {
        Bson match = Aggregates.match(query);

        // add all group-by fields to the projection together with the aggregation field name
        List<String> groupByFields = new ArrayList<>(groupByField);
        groupByFields.add(idField);
        Bson project = Aggregates.project(Projections.include(groupByFields));

        // _id document creation to have the multiple id
        Document id = new Document();
        for (String s : groupByField) {
            id.append(s, "$" + s);
        }
        Bson group;
        if (count) {
            group = Aggregates.group(id, Accumulators.sum("count", 1));
        } else {
            group = Aggregates.group(id, Accumulators.addToSet("features", "$" + idField));
        }
        return Arrays.asList(match, project, group);
    }
}

From source file:org.opencb.commons.datastore.mongodb.MongoDBQueryUtils.java

License:Apache License

protected static Bson getProjection(Bson projection, QueryOptions options) {
    Bson projectionResult = null;//  w  ww. ja  va 2  s .  c om
    List<Bson> projections = new ArrayList<>();

    // It is too risky to merge projections, if projection alrady exists we return it as it is, otherwise we create a new one.
    if (projection != null) {
        //            projections.add(projection);
        return projection;
    }

    if (options != null) {
        // Select which fields are excluded and included in the query
        // Read and process 'include'/'exclude'/'elemMatch' field from 'options' object

        Bson include = null;
        if (options.containsKey(QueryOptions.INCLUDE)) {
            Object includeObject = options.get(QueryOptions.INCLUDE);
            if (includeObject != null) {
                if (includeObject instanceof Bson) {
                    include = (Bson) includeObject;
                } else {
                    List<String> includeStringList = options.getAsStringList(QueryOptions.INCLUDE, ",");
                    if (includeStringList != null && includeStringList.size() > 0) {
                        include = Projections.include(includeStringList);
                    }
                }
            }
        }

        Bson exclude = null;
        boolean excludeId = false;
        if (options.containsKey(QueryOptions.EXCLUDE)) {
            Object excludeObject = options.get(QueryOptions.EXCLUDE);
            if (excludeObject != null) {
                if (excludeObject instanceof Bson) {
                    exclude = (Bson) excludeObject;
                } else {
                    List<String> excludeStringList = options.getAsStringList(QueryOptions.EXCLUDE, ",");
                    if (excludeStringList != null && excludeStringList.size() > 0) {
                        exclude = Projections.exclude(excludeStringList);
                        excludeId = excludeStringList.contains("_id");
                    }
                }
            }
        }

        // If both include and exclude exist we only add include
        if (include != null) {
            projections.add(include);
            // MongoDB allows to exclude _id when include is present
            if (excludeId) {
                projections.add(Projections.excludeId());
            }
        } else {
            if (exclude != null) {
                projections.add(exclude);
            }
        }

        if (options.containsKey(MongoDBCollection.ELEM_MATCH)) {
            Object elemMatch = options.get(MongoDBCollection.ELEM_MATCH);
            if (elemMatch != null && elemMatch instanceof Bson) {
                projections.add((Bson) elemMatch);
            }
        }

        //            List<String> includeStringList = options.getAsStringList(MongoDBCollection.INCLUDE, ",");
        //            if (includeStringList != null && includeStringList.size() > 0) {
        //                projections.add(Projections.include(includeStringList));
        ////                for (Object field : includeStringList) {
        ////                    projection.put(field.toString(), 1);
        ////                }
        //            } else {
        //                List<String> excludeStringList = options.getAsStringList(MongoDBCollection.EXCLUDE, ",");
        //                if (excludeStringList != null && excludeStringList.size() > 0) {
        //                    projections.add(Projections.exclude(excludeStringList));
        ////                    for (Object field : excludeStringList) {
        ////                        projection.put(field.toString(), 0);
        ////                    }
        //                }
        //            }
    }

    if (projections.size() > 0) {
        projectionResult = Projections.fields(projections);
    }

    return projectionResult;
}

From source file:org.opencb.opencga.catalog.db.mongodb.AbstractCatalogMongoDBAdaptor.java

License:Apache License

protected QueryResult groupBy(MongoDBCollection collection, Bson query, List<String> groupByField,
        String idField, QueryOptions options) {
    if (groupByField == null || groupByField.isEmpty()) {
        return new QueryResult();
    }//from  w  w  w .  j  ava 2  s . c  om

    if (groupByField.size() == 1) {
        // if only one field then we call to simple groupBy
        return groupBy(collection, query, groupByField.get(0), idField, options);
    } else {
        Bson match = Aggregates.match(query);

        // add all group-by fields to the projection together with the aggregation field name
        List<String> groupByFields = new ArrayList<>(groupByField);
        groupByFields.add(idField);
        Bson project = Aggregates.project(Projections.include(groupByFields));

        // _id document creation to have the multiple id
        Document id = new Document();
        for (String s : groupByField) {
            id.append(s, "$" + s);
        }
        Bson group;
        if (options.getBoolean("count", false)) {
            group = Aggregates.group(id, Accumulators.sum("count", 1));
        } else {
            group = Aggregates.group(id, Accumulators.addToSet("features", "$" + idField));
        }
        return collection.aggregate(Arrays.asList(match, project, group), options);
    }
}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoMetaDBAdaptor.java

License:Apache License

@Override
public QueryResult<AuthenticationOrigin> getAuthenticationOrigin(String authId) throws CatalogDBException {
    long startTime = startQuery();

    Bson match = Aggregates.match(Filters.eq(PRIVATE_ID, "METADATA"));
    Bson unwind = Aggregates.unwind("$authenticationOrigins");
    Bson match2 = Aggregates.match(Filters.in("authenticationOrigins.id", authId));
    Bson project = Aggregates.project(Projections.include("authenticationOrigins"));

    QueryResult<Document> aggregate = metaCollection.aggregate(Arrays.asList(match, unwind, match2, project),
            null);//from  w  ww .java2  s.  c om
    AuthenticationOrigin result = null;
    if (aggregate.getNumResults() == 1) {
        result = parseObject(((Document) aggregate.getResult().get(0).get("authenticationOrigins")),
                AuthenticationOrigin.class);
    }
    return endQuery("get authenticationOrigin", startTime, Arrays.asList(result));
}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoProjectDBAdaptor.java

License:Apache License

@Override
public long getProjectId(String userId, String projectAlias) throws CatalogDBException {
    QueryResult<Document> queryResult = userCollection.find(
            new BsonDocument("projects.alias", new BsonString(projectAlias)).append("id",
                    new BsonString(userId)),
            Projections.fields(Projections.include("projects.id"),
                    Projections.elemMatch("projects", Filters.eq("alias", projectAlias))),
            null);//from   w  w w.j ava 2 s.  c om
    /*
            QueryResult<DBObject> queryResult = userCollection.find(
        BasicDBObjectBuilder
                .start("projects.alias", projectAlias)
                .append("id", userId).get(),
        BasicDBObjectBuilder.start("projects.id", true)
                .append("projects", new BasicDBObject("$elemMatch", new BasicDBObject("alias", projectAlias))).get(),
        null
            );*/
    User user = parseUser(queryResult);
    if (user == null || user.getProjects().isEmpty()) {
        return -1;
    } else {
        return user.getProjects().get(0).getId();
    }
}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoProjectDBAdaptor.java

License:Apache License

@Override
public String getProjectOwnerId(long projectId) throws CatalogDBException {
    //        DBObject query = new BasicDBObject("projects.id", projectId);
    Bson query = Filters.eq("projects.id", projectId);

    //        DBObject projection = new BasicDBObject("id", "true");
    Bson projection = Projections.include("id");

    //        QueryResult<DBObject> result = userCollection.find(query, projection, null);
    QueryResult<Document> result = userCollection.find(query, projection, null);

    if (result.getResult().isEmpty()) {
        throw CatalogDBException.idNotFound("Project", projectId);
    } else {//w w  w.j  a  v a  2 s .  c o m
        return result.getResult().get(0).get("id").toString();
    }
}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoProjectDBAdaptor.java

License:Apache License

@Override
public QueryResult<Project> get(Query query, QueryOptions options) throws CatalogDBException {
    long startTime = startQuery();
    if (!query.containsKey(QueryParams.STATUS_NAME.key())) {
        query.append(QueryParams.STATUS_NAME.key(), "!=" + Status.TRASHED + ";!=" + Status.DELETED);
    }/*from  w w w .  j a  v a 2s  .co  m*/
    List<Bson> aggregates = new ArrayList<>();

    aggregates.add(Aggregates.unwind("$projects"));
    aggregates.add(Aggregates.match(parseQuery(query)));

    // Check include
    if (options != null && options.get(QueryOptions.INCLUDE) != null) {
        List<String> includeList = new ArrayList<>();
        List<String> optionsAsStringList = options.getAsStringList(QueryOptions.INCLUDE);
        includeList.addAll(optionsAsStringList.stream().collect(Collectors.toList()));
        if (!includeList.contains(QueryParams.ID.key())) {
            includeList.add(QueryParams.ID.key());
        }

        // Check if they start with projects.
        for (int i = 0; i < includeList.size(); i++) {
            if (!includeList.get(i).startsWith("projects.")) {
                String param = "projects." + includeList.get(i);
                includeList.set(i, param);
            }
        }
        if (includeList.size() > 0) {
            aggregates.add(Aggregates.project(Projections.include(includeList)));
        }
    }

    QueryResult<Project> projectQueryResult = userCollection.aggregate(aggregates, projectConverter, options);

    if (options == null || !options.containsKey(QueryOptions.EXCLUDE)
            || !options.getAsStringList(QueryOptions.EXCLUDE).contains("projects.studies")) {
        for (Project project : projectQueryResult.getResult()) {
            Query studyQuery = new Query(CatalogStudyDBAdaptor.QueryParams.PROJECT_ID.key(), project.getId());
            try {
                QueryResult<Study> studyQueryResult = dbAdaptorFactory.getCatalogStudyDBAdaptor()
                        .get(studyQuery, options);
                project.setStudies(studyQueryResult.getResult());
            } catch (CatalogDBException e) {
                e.printStackTrace();
            }
        }
    }

    return endQuery("Get project", startTime, projectQueryResult.getResult());
}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoProjectDBAdaptor.java

License:Apache License

@Override
public QueryResult nativeGet(Query query, QueryOptions options) throws CatalogDBException {
    if (!query.containsKey(QueryParams.STATUS_NAME.key())) {
        query.append(QueryParams.STATUS_NAME.key(), "!=" + Status.TRASHED + ";!=" + Status.DELETED);
    }/* ww  w.  ja v a2s. c o  m*/
    List<Bson> aggregates = new ArrayList<>();
    aggregates.add(Aggregates.match(parseQuery(query)));
    aggregates.add(Aggregates.unwind("$projects"));

    // Check include & excludes
    if (options != null && options.get(QueryOptions.INCLUDE) != null) {
        List<String> includeList = new ArrayList<>();
        List<String> optionsAsStringList = options.getAsStringList(QueryOptions.INCLUDE);
        includeList.addAll(optionsAsStringList.stream().collect(Collectors.toList()));

        if (includeList.size() > 0) {
            aggregates.add(Aggregates.project(Projections.include(includeList)));
        }
    }

    QueryResult<Document> projectQueryResult = userCollection.aggregate(aggregates, options);
    ArrayList<Document> returnedProjectList = new ArrayList<>();

    for (Document user : projectQueryResult.getResult()) {
        Document project = (Document) user.get("projects");
        Query studyQuery = new Query(CatalogStudyDBAdaptor.QueryParams.PROJECT_ID.key(), project.get("id"));
        QueryResult studyQueryResult = dbAdaptorFactory.getCatalogStudyDBAdaptor().nativeGet(studyQuery,
                options);
        project.remove("studies");
        project.append("studies", studyQueryResult.getResult());
        returnedProjectList.add(project);
    }

    projectQueryResult.setResult(returnedProjectList);

    return projectQueryResult;

}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoStudyDBAdaptor.java

License:Apache License

@Override
public QueryResult<Group> getGroup(long studyId, @Nullable String groupId, List<String> userIds)
        throws CatalogDBException {
    long startTime = startQuery();
    checkStudyId(studyId);//from  ww w  .j  a va 2  s.  c o  m
    for (String userId : userIds) {
        dbAdaptorFactory.getCatalogUserDBAdaptor().checkUserExists(userId);
    }
    if (groupId != null && groupId.length() > 0 && !groupExists(studyId, groupId)) {
        throw new CatalogDBException("Group \"" + groupId + "\" does not exist in study " + studyId);
    }

    /*
    * List<Bson> aggregation = new ArrayList<>();
    aggregation.add(Aggregates.match(Filters.elemMatch(QueryParams.VARIABLE_SET.key(),
        Filters.eq(VariableSetParams.ID.key(), variableSetId))));
    aggregation.add(Aggregates.project(Projections.include(QueryParams.VARIABLE_SET.key())));
    aggregation.add(Aggregates.unwind("$" + QueryParams.VARIABLE_SET.key()));
    aggregation.add(Aggregates.match(Filters.eq(QueryParams.VARIABLE_SET_ID.key(), variableSetId)));
    QueryResult<VariableSet> queryResult = studyCollection.aggregate(aggregation, variableSetConverter, new QueryOptions());
    * */
    List<Bson> aggregation = new ArrayList<>();
    aggregation.add(Aggregates.match(Filters.eq(PRIVATE_ID, studyId)));
    aggregation.add(Aggregates.project(Projections.include(QueryParams.GROUPS.key())));
    aggregation.add(Aggregates.unwind("$" + QueryParams.GROUPS.key()));

    //        Document query = new Document(PRIVATE_ID, studyId);
    //        List<Bson> groupQuery = new ArrayList<>();
    if (userIds.size() > 0) {
        aggregation.add(Aggregates.match(Filters.in(QueryParams.GROUP_USER_IDS.key(), userIds)));
        //            groupQuery.add(Filters.in("userIds", userIds));
    }
    if (groupId != null && groupId.length() > 0) {
        aggregation.add(Aggregates.match(Filters.eq(QueryParams.GROUP_NAME.key(), groupId)));
        //            groupQuery.add(Filters.eq("id", groupId));
    }

    //        Bson projection = new Document(QueryParams.GROUPS.key(), new Document("$elemMatch", groupQuery));

    QueryResult<Document> queryResult = studyCollection.aggregate(aggregation, null);

    //        QueryResult<Document> queryResult = studyCollection.find(query, projection, null);
    List<Study> studies = CatalogMongoDBUtils.parseStudies(queryResult);
    List<Group> groups = new ArrayList<>();
    studies.stream().filter(study -> study.getGroups() != null)
            .forEach(study -> groups.addAll(study.getGroups()));
    return endQuery("getGroup", startTime, groups);
}

From source file:org.opencb.opencga.catalog.db.mongodb.CatalogMongoStudyDBAdaptor.java

License:Apache License

@Override
public Long variableSetExists(long variableSetId) {
    List<Bson> aggregation = new ArrayList<>();
    aggregation.add(Aggregates.match(Filters.elemMatch(QueryParams.VARIABLE_SET.key(),
            Filters.eq(VariableSetParams.ID.key(), variableSetId))));
    aggregation.add(Aggregates.project(Projections.include(QueryParams.VARIABLE_SET.key())));
    aggregation.add(Aggregates.unwind("$" + QueryParams.VARIABLE_SET.key()));
    aggregation.add(Aggregates.match(Filters.eq(QueryParams.VARIABLE_SET_ID.key(), variableSetId)));
    QueryResult<VariableSet> queryResult = studyCollection.aggregate(aggregation, variableSetConverter,
            new QueryOptions());

    return (long) queryResult.getResult().size();
}