Example usage for com.mongodb DBCollection distinct

List of usage examples for com.mongodb DBCollection distinct

Introduction

In this page you can find the example usage for com.mongodb DBCollection distinct.

Prototype

@SuppressWarnings("unchecked")
public List distinct(final String fieldName, final DBCollectionDistinctOptions options) 

Source Link

Document

Find the distinct values for a specified field across a collection and returns the results in an array.

Usage

From source file:org.fastmongo.odm.bson.repository.BsonMongoTemplate.java

License:Apache License

/**
 * Finds the distinct values for a specified field across a collection and returns the results in a List.
 *
 * @param clazz the collection class.//from   w w  w.  j  a  va2 s.c  o  m
 * @param key   Specifies the field for which to return the distinct values.
 * @param query specifies the selection query to determine the subset of documents
 *              from which to retrieve the distinct values.
 * @return A {@code List} of the distinct values
 */
@SuppressWarnings("unchecked")
public <T> List<T> distinct(Class<?> clazz, String key, Query query) {
    DBCollection collection = getCollection(clazz);
    return collection.distinct(key, query != null ? query.toDbObject() : null);
}

From source file:org.fastmongo.odm.repository.MongoTemplate.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public <T> List<T> distinct(String collectionName, String key, Query query) {
    DBCollection collection = getCollection(collectionName);
    return collection.distinct(key, query.toDbObject());
}

From source file:org.fastmongo.odm.repository.MongoTemplate.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//w  ww  .j a  v a  2  s. co m
public <T> List<T> distinct(Class<?> collectionClass, String key, Query query) {
    DBCollection collection = getCollection(getCollectionName(collectionClass));
    return collection.distinct(key, query.toDbObject());
}

From source file:org.grails.datastore.mapping.mongo.query.MongoQuery.java

License:Apache License

@SuppressWarnings("hiding")
@Override//from   ww  w.j  a v  a  2 s.c om
protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
    final MongoTemplate template = mongoSession.getMongoTemplate(entity);

    return template.execute(new DbCallback<List>() {
        @SuppressWarnings("unchecked")
        public List doInDB(DB db) throws MongoException, DataAccessException {

            final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
            if (uniqueResult) {
                final DBObject dbObject;
                if (criteria.isEmpty()) {
                    if (entity.isRoot()) {
                        dbObject = collection.findOne();
                    } else {
                        dbObject = collection.findOne(new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD,
                                entity.getDiscriminator()));
                    }
                } else {
                    dbObject = collection.findOne(getMongoQuery());
                }
                return wrapObjectResultInList(createObjectFromDBObject(dbObject));
            }

            DBCursor cursor = null;
            DBObject query = createQueryObject(entity);

            final List<Projection> projectionList = projections().getProjectionList();
            if (projectionList.isEmpty()) {
                cursor = executeQuery(entity, criteria, collection, query);
                return (List) new MongoResultList(cursor, mongoEntityPersister).clone();
            }

            List projectedResults = new ArrayList();
            for (Projection projection : projectionList) {
                if (projection instanceof CountProjection) {
                    // For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
                    //projectedResults.add(collection.getCount(query));
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    projectedResults.add(cursor.size());
                } else if (projection instanceof MinProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    MinProjection mp = (MinProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.min((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));
                } else if (projection instanceof MaxProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    MaxProjection mp = (MaxProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.max((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));
                } else if (projection instanceof CountDistinctProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    CountDistinctProjection mp = (CountDistinctProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.countDistinct((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));

                } else if ((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) {
                    final PersistentProperty persistentProperty;
                    final String propertyName;
                    if (projection instanceof IdProjection) {
                        persistentProperty = entity.getIdentity();
                        propertyName = MongoEntityPersister.MONGO_ID_FIELD;
                    } else {
                        PropertyProjection pp = (PropertyProjection) projection;
                        persistentProperty = entity.getPropertyByName(pp.getPropertyName());
                        propertyName = getPropertyName(entity, persistentProperty.getName());
                    }
                    if (persistentProperty != null) {
                        populateMongoQuery(entity, query, criteria);

                        List propertyResults = null;
                        if (max > -1) {
                            // if there is a limit then we have to do a manual projection since the MongoDB driver doesn't support limits and distinct together
                            cursor = executeQueryAndApplyPagination(collection, query);
                            propertyResults = manualProjections
                                    .property(new MongoResultList(cursor, mongoEntityPersister), propertyName);
                        } else {

                            propertyResults = collection.distinct(propertyName, query);
                        }

                        if (persistentProperty instanceof ToOne) {
                            Association a = (Association) persistentProperty;
                            propertyResults = session.retrieveAll(a.getAssociatedEntity().getJavaClass(),
                                    propertyResults);
                        }

                        if (projectedResults.size() == 0 && projectionList.size() == 1) {
                            return propertyResults;
                        }
                        projectedResults.add(propertyResults);
                    } else {
                        throw new InvalidDataAccessResourceUsageException(
                                "Cannot use [" + projection.getClass().getSimpleName()
                                        + "] projection on non-existent property: " + propertyName);
                    }
                }
            }

            return projectedResults;
        }

        protected DBCursor executeQuery(final PersistentEntity entity, final Junction criteria,
                final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            if (criteria.isEmpty()) {
                cursor = executeQueryAndApplyPagination(collection, query);
            } else {
                populateMongoQuery(entity, query, criteria);
                cursor = executeQueryAndApplyPagination(collection, query);
            }

            if (queryArguments != null) {
                if (queryArguments.containsKey(HINT_ARGUMENT)) {
                    Object hint = queryArguments.get(HINT_ARGUMENT);
                    if (hint instanceof Map) {
                        cursor.hint(new BasicDBObject((Map) hint));
                    } else if (hint != null) {
                        cursor.hint(hint.toString());
                    }

                }
            }
            return cursor;
        }

        protected DBCursor executeQueryAndApplyPagination(final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            cursor = collection.find(query);
            if (offset > 0) {
                cursor.skip(offset);
            }
            if (max > -1) {
                cursor.limit(max);
            }

            if (!orderBy.isEmpty()) {
                DBObject orderObject = new BasicDBObject();
                for (Order order : orderBy) {
                    String property = order.getProperty();
                    property = getPropertyName(entity, property);
                    orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1);
                }
                cursor.sort(orderObject);
            } else {
                MongoCollection coll = (MongoCollection) entity.getMapping().getMappedForm();
                if (coll != null && coll.getSort() != null) {
                    DBObject orderObject = new BasicDBObject();
                    Order order = coll.getSort();
                    String property = order.getProperty();
                    property = getPropertyName(entity, property);
                    orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1);
                    cursor.sort(orderObject);
                }

            }

            return cursor;
        }
    });
}

From source file:org.jewzaam.mongo.MongoCRUD.java

License:Open Source License

protected <T> Iterator<T> distinct(String collectionName, String key, String jsonQuery) {
    initialize();//from  ww w.j  a v  a  2  s. c  o  m
    DBCollection coll = db.getCollection(collectionName);

    DBObject query = null;

    if (jsonQuery != null && !jsonQuery.isEmpty()) {
        query = converter.fromJson(jsonQuery, BasicDBObject.class);
    }

    List<T> output = (List<T>) coll.distinct(key, query);
    return output.iterator();
}

From source file:org.springframework.datastore.mapping.mongo.query.MongoQuery.java

License:Apache License

@Override
protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
    final MongoTemplate template = mongoSession.getMongoTemplate(entity);

    return template.execute(new DbCallback<List>() {
        @Override// w w w.java 2 s .  c  o m
        public List doInDB(DB db) throws MongoException, DataAccessException {

            final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
            if (uniqueResult) {
                final DBObject dbObject;
                if (criteria.isEmpty()) {
                    if (entity.isRoot()) {
                        dbObject = collection.findOne();
                    } else {
                        DBObject query = new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD,
                                entity.getDiscriminator());
                        dbObject = collection.findOne(query);
                    }
                } else {
                    DBObject query = getMongoQuery();

                    dbObject = collection.findOne(query);
                }
                final Object object = createObjectFromDBObject(dbObject);
                return wrapObjectResultInList(object);
            } else {
                DBCursor cursor;
                DBObject query = createQueryObject(entity);

                final List<Projection> projectionList = projections().getProjectionList();
                if (projectionList.isEmpty()) {
                    cursor = executeQuery(entity, criteria, collection, query);
                    return new MongoResultList(cursor, mongoEntityPersister);
                } else {
                    List projectedResults = new ArrayList();
                    for (Projection projection : projectionList) {
                        if (projection instanceof CountProjection) {
                            // For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
                            //projectedResults.add(collection.getCount(query));
                            cursor = executeQuery(entity, criteria, collection, query);
                            projectedResults.add(cursor.size());
                        } else if (projection instanceof MinProjection) {
                            cursor = executeQuery(entity, criteria, collection, query);
                            MinProjection mp = (MinProjection) projection;

                            MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                            projectedResults.add(
                                    manualProjections.min((Collection) results.clone(), mp.getPropertyName()));
                        } else if (projection instanceof MaxProjection) {
                            cursor = executeQuery(entity, criteria, collection, query);
                            MaxProjection mp = (MaxProjection) projection;

                            MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                            projectedResults.add(
                                    manualProjections.max((Collection) results.clone(), mp.getPropertyName()));
                        } else if ((projection instanceof PropertyProjection)
                                || (projection instanceof IdProjection)) {
                            final PersistentProperty persistentProperty;
                            final String propertyName;
                            if (projection instanceof IdProjection) {
                                persistentProperty = entity.getIdentity();
                                propertyName = MongoEntityPersister.MONGO_ID_FIELD;
                            } else {
                                PropertyProjection pp = (PropertyProjection) projection;
                                persistentProperty = entity.getPropertyByName(pp.getPropertyName());
                                propertyName = pp.getPropertyName();
                            }
                            if (persistentProperty != null) {
                                populateMongoQuery(entity, query, criteria);
                                List propertyResults = collection.distinct(propertyName, query);

                                if (persistentProperty instanceof ToOne) {
                                    Association a = (Association) persistentProperty;
                                    propertyResults = session.retrieveAll(
                                            a.getAssociatedEntity().getJavaClass(), propertyResults);
                                }

                                if (projectedResults.size() == 0 && projectionList.size() == 1) {
                                    return propertyResults;
                                } else {
                                    projectedResults.add(propertyResults);
                                }
                            } else {
                                throw new InvalidDataAccessResourceUsageException(
                                        "Cannot use [" + projection.getClass().getSimpleName()
                                                + "] projection on non-existent property: " + propertyName);
                            }
                        }
                    }

                    return projectedResults;
                }

            }
        }

        protected DBCursor executeQuery(final PersistentEntity entity, final Junction criteria,
                final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            if (criteria.isEmpty()) {
                cursor = executeQueryAndApplyPagination(collection, query);
            } else {

                populateMongoQuery(entity, query, criteria);

                cursor = executeQueryAndApplyPagination(collection, query);

            }
            return cursor;
        }

        protected DBCursor executeQueryAndApplyPagination(final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            cursor = collection.find(query);
            if (offset > 0) {
                cursor.skip(offset);
            }
            if (max > -1) {
                cursor.limit(max);
            }

            for (Order order : orderBy) {
                DBObject orderObject = new BasicDBObject();
                orderObject.put(order.getProperty(), order.getDirection() == Order.Direction.DESC ? -1 : 1);
                cursor.sort(orderObject);
            }

            return cursor;
        }

    });
}

From source file:vn.chodientu.repository.ItemCrawlLogRepository.java

public List<String> listSellerUniq(long startTime, long endTime) {
    DBCollection myColl = getMongo().getCollection("itemCrawlLog");
    BasicDBObject gtQuery = new BasicDBObject();
    gtQuery.put("time", new BasicDBObject("$gte", startTime).append("$lt", endTime));
    List listSellerUnique = myColl.distinct("sellerId", gtQuery);
    return listSellerUnique;
}

From source file:yelpmongodb.hw4.java

private void checkMainCategories() {
    ArrayList<String> list = getCategories(mainCategoriesPanel);
    ArrayList<String> attList = new ArrayList<>();
    removeComponents(attributesPanel, attributesScrollBar);
    MongoClient client = new MongoClient();
    DB db = client.getDB("db");
    DBCollection coll = db.getCollection("business");
    String attribute = "";

    if (list.size() > 0) {
        DBObject mainQuery = mainCategoriesQuery(list, 0);
        List curs = coll.distinct("attributes", mainQuery);

        for (int i = 0; i < curs.size(); i++) {
            BasicDBObject dbo = (BasicDBObject) curs.get(i);

            for (Entry<String, Object> entry : dbo.entrySet()) {
                if (entry.getValue() instanceof BasicDBObject) {
                    BasicDBObject nestedobj = (BasicDBObject) entry.getValue();
                    for (Entry<String, Object> nestedentry : nestedobj.entrySet()) {
                        attribute = entry.getKey() + ":" + nestedentry.getKey() + ":" + nestedentry.getValue();
                    }/*  w  w  w .  j av a2s . c  o  m*/
                } else {
                    attribute = entry.getKey() + ":" + entry.getValue();
                }
                if (!(attList.contains(attribute))) {
                    attList.add(attribute);
                }
            }
        }

        createAttributeCheckBox(attList);
        client.close();
    }
}