Example usage for com.mongodb DBCollection find

List of usage examples for com.mongodb DBCollection find

Introduction

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

Prototype

public DBCursor find(final DBObject query) 

Source Link

Document

Select documents in collection and get a cursor to the selected documents.

Usage

From source file:com.fileoperations.CopyClass.java

public CopyClass(String userID, String parentPath, String name, String newPath) throws UnknownHostException {
    this.userID = userID;
    this.parentPath = parentPath;
    this.name = name;
    this.newPath = newPath;
    mymongo = new Connection();
    DBCollection usercol = mymongo.getMembersCol();
    BasicDBObject query = new BasicDBObject();
    query.put("_id", userID);
    DBCursor cursor = usercol.find(query);
    DBObject col = cursor.next();/*from   w ww .  jav a  2s  . c om*/
    userCollectionName = col.get("collection").toString();
    collection = mymongo.getCollection(userCollectionName);
}

From source file:com.fileoperations.FolderDownload.java

public FolderDownload(String userID, String parentPath, String folderName) throws UnknownHostException {
    this.userID = userID;
    this.parentPath = parentPath;
    this.folderName = folderName;
    mymongo = new Connection();
    DBCollection usercol = mymongo.getMembersCol();
    BasicDBObject query = new BasicDBObject();
    query.put("_id", userID);
    DBCursor cursor = usercol.find(query);
    DBObject col = cursor.next();//from   w w w.  java2  s. c om
    userCollectionName = col.get("collection").toString();
    collection = mymongo.getCollection(userCollectionName);
}

From source file:com.fileoperations.RenameFolder.java

public RenameFolder(String userID, String parentPath, String oldName, String newName)
        throws UnknownHostException {
    this.userID = userID;
    this.parentPath = parentPath;
    this.oldName = oldName;
    this.newName = newName;
    mymongo = new Connection();
    DBCollection usercol = mymongo.getMembersCol();
    BasicDBObject query = new BasicDBObject();
    query.put("_id", userID);
    DBCursor cursor = usercol.find(query);
    DBObject col = cursor.next();//from w  w w  .j  a  v a  2s.  c  o  m
    userCollectionName = col.get("collection").toString();
    collection = mymongo.getCollection(userCollectionName);
}

From source file:com.foodtruckdata.mongodb.UsersInput.java

@Override
public void AddSchedule(Date dateTime, String address, String truck_id) {
    //remove all outdated schedules
    BasicDBObject filter = new BasicDBObject("_id", new ObjectId(truck_id));
    DBCollection coll = mongoDB.getCollection("Trucks");
    Cursor cursor = coll.find(filter);
    if (cursor.hasNext()) {
        BasicDBObject truck = (BasicDBObject) cursor.next();
        BasicDBObject[] schedules = (BasicDBObject[]) truck.get("Schedules");
        for (BasicDBObject schedule : schedules) {
            if (((Date) schedule.get("Time")).compareTo(new Date()) < 0) {
                coll.update(filter, (new BasicDBObject("$pull", (new BasicDBObject("Schedules", schedule)))));
            }//w  w  w  . j a  v a  2s.com
        }
    }
    //insert the new schedule
    if (dateTime.compareTo((new Date())) > 0) {
        BasicDBObject schedule = new BasicDBObject();
        schedule.put("Time", dateTime);
        schedule.put("Address", address);
        //put lat long also
        coll.update(filter, (new BasicDBObject("$addToSet", (new BasicDBObject("Schedules", schedule)))));
    }
}

From source file:com.fpt.xml.hth.db.lib.DAO.MovieDAO.java

/**
 * get list movies by param city/*from  w  w  w.j ava 2s.  c  o m*/
 *
 * @param city
 * @return List<MovieTheaterSessionDTO>
 */
public List<MovieTheaterSessionDTO> getAllByCity(String city) {
    connection();
    List<MovieTheaterSessionDTO> lst = new ArrayList<MovieTheaterSessionDTO>();
    DBCollection collection = movieCollection;

    BasicDBObject dbObject = new BasicDBObject();
    dbObject.append("theaters", new BasicDBObject("$elemMatch", new BasicDBObject("theater.city", city)));

    DBCursor cursor = collection.find(dbObject);

    while (cursor.hasNext()) {
        BasicDBObject basic = (BasicDBObject) cursor.next();
        MovieTheaterSessionDTO movieDto = converter.convertBasicObjectToModel(basic);
        //            List<TheaterSessionDTO> lstTheaterSession = new ArrayList<TheaterSessionDTO>();
        //            if (city != null && !city.isEmpty()) {
        //                for (TheaterSessionDTO theaterDTO : movieDto.getTheaters()) {
        //                    if (theaterDTO.getTheater().getCity().equals(city)) {                
        //                        lstTheaterSession.add(theaterDTO);
        //                    }
        //                }
        //            }
        //            movieDto.setTheaters(lstTheaterSession);
        lst.add(movieDto);
    }
    cursor.close();
    mongoClient.close();
    return lst;
}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public List<Map<String, String>> provide(GatfTestDataProvider provider, AcceptanceTestContext context) {

    List<Map<String, String>> result = new ArrayList<Map<String, String>>();

    Assert.assertNotNull("provider cannot be null", provider);
    Assert.assertTrue("provider cannot be null", provider.getArgs() != null && provider.getArgs().length > 0);
    Assert.assertNotNull("mongodb-collection cannot be empty", provider.getArgs()[0]);
    Assert.assertNotNull("queryString cannot be empty", provider.getQueryStr());
    Assert.assertNotNull("variableNames cannot be empty", provider.getSourceProperties());
    Assert.assertNotNull("propertyNames cannot be empty", provider.getProviderProperties());

    String dbName = args[2].trim();
    String collName = provider.getArgs()[0].trim();
    String queryString = provider.getQueryStr().trim();
    String variableNames = provider.getProviderProperties();
    String propertyNames = provider.getSourceProperties();

    Assert.assertNotNull("mongodb-collection cannot be empty", collName.isEmpty());
    Assert.assertFalse("queryString cannot be empty", queryString.isEmpty());

    List<String> variableNamesArr = new ArrayList<String>();
    for (String varName : variableNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            variableNamesArr.add(varName);
        }//  ww w.  java 2s  .  c  o m
    }
    Assert.assertTrue("need to define at-least a single variable name",
            !variableNames.isEmpty() && variableNames.split(",").length > 0 && variableNamesArr.size() > 0);

    List<String> propertyNamesArr = new ArrayList<String>();
    for (String varName : propertyNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            propertyNamesArr.add(varName);
        }
    }
    Assert.assertTrue("need to define at-least a single property name",
            !propertyNames.isEmpty() && propertyNames.split(",").length > 0 && propertyNamesArr.size() > 0);

    Assert.assertTrue("property name and variable name sizes don't match",
            propertyNamesArr.size() == variableNamesArr.size());

    StringBuilder build = new StringBuilder();
    build.append("Provider configuration [\n");
    build.append(String.format("dataSource name is %s\n", getDataSourceName()));
    build.append(String.format("mongodb-collection is %s\n", collName));
    build.append(String.format("queryString is %s\n", queryString));
    build.append(String.format("propertyNames is %s\n", propertyNames));
    build.append(String.format("variableNames is %s]", variableNames));
    logger.info(build.toString());

    Resource res = null;
    try {

        res = getResource();
        MongoClient mongoClient = (MongoClient) res.object;

        DB db = null;
        try {
            db = mongoClient.getDB(dbName);

            DBCollection coll = db.getCollection(collName);
            Assert.assertNotNull(String.format("Mongodb collection %s not found", collName), coll);

            DBObject queryObject = null;
            try {
                queryObject = (DBObject) JSON.parse(queryString);
            } catch (Exception e) {
                Assert.assertNotNull("queryString passed is invalid");
            }

            DBCursor cursor = null;
            try {
                cursor = coll.find(queryObject);
                while (cursor.hasNext()) {
                    DBObject object = cursor.next();
                    Map<String, String> row = new HashMap<String, String>();
                    for (int i = 0; i < variableNamesArr.size(); i++) {
                        Assert.assertTrue(
                                String.format("Could not find %s field in the result document returned",
                                        propertyNamesArr.get(i)),
                                object.containsField(propertyNamesArr.get(i)));
                        row.put(variableNamesArr.get(i), object.get(propertyNamesArr.get(i)).toString());
                    }
                    result.add(row);
                }
            } catch (Exception e) {
                throw new AssertionError(e);
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        } catch (Exception e) {
            throw new AssertionError(
                    String.format("Fetching Test Data failed while executing query %s with the error %s",
                            queryString, ExceptionUtils.getStackTrace(e)));
        } finally {
            if (mongoClient != null)
                mongoClient.close();
        }
    } catch (Exception e) {
        throw new AssertionError(
                String.format("Fetching Test Data failed while executing query %s with the error %s",
                        queryString, ExceptionUtils.getStackTrace(e)));
    } finally {
        if (res != null)
            releaseToPool(res);
    }
    return result;
}

From source file:com.gigaspaces.persistency.datasource.MongoSqlQueryDataIterator.java

License:Open Source License

private void init() {
    DBCollection collection = client.getCollection(query.getTypeDescriptor().getTypeName());

    BasicDBObjectBuilder q = BasicDBObjectBuilder.start();

    logger.debug(query);/*w  w  w .  java  2  s  .  co  m*/

    if (query.supportsAsSQLQuery())
        q = MongoQueryFactory.create(query);
    else if (query.supportsTemplateAsDocument()) {
        Map m = new DefaultSpaceDocumentMapper(query.getTypeDescriptor())
                .toDBObject(query.getTemplateAsDocument()).toMap();

        q = BasicDBObjectBuilder.start(m);
    }

    cursor = collection.find(q.get());
}

From source file:com.gigaspaces.persistency.MongoClientConnector.java

License:Open Source License

public Collection<SpaceTypeDescriptor> loadMetadata() {

    DBCollection metadata = getCollection(METADATA_COLLECTION_NAME);

    DBCursor cursor = metadata.find(new BasicDBObject());

    while (cursor.hasNext()) {
        DBObject type = cursor.next();//from   w ww .jav  a 2 s .c om

        Object b = type.get(TYPE_DESCRIPTOR_FIELD_NAME);

        readMetadata(b);
    }

    return getSortedTypes();
}

From source file:com.gigaspaces.persistency.MongoSpaceDataSource.java

License:Open Source License

@Override
public DataIterator<Object> getDataIteratorByIds(DataSourceIdsQuery idsQuery) {

    if (logger.isDebugEnabled())
        logger.debug("MongoSpaceDataSource.getDataIteratorByIds(" + idsQuery + ")");

    DBObject[] ors = new DBObject[idsQuery.getIds().length];

    for (int i = 0; i < ors.length; i++)
        ors[i] = BasicDBObjectBuilder.start().add(Constants.ID_PROPERTY, idsQuery.getIds()[i]).get();

    DBObject document = QueryBuilder.start().or(ors).get();

    DBCollection mongoCollection = mongoClient.getCollection(idsQuery.getTypeDescriptor().getTypeName());

    DBCursor results = mongoCollection.find(document);

    return new DefaultMongoDataIterator(results, idsQuery.getTypeDescriptor());
}

From source file:com.glaf.wechat.mongodb.service.impl.WxMongoDBLogServiceImpl.java

License:Apache License

public List<WxLog> getWxLogsByQueryCriteria(int start, int pageSize, WxLogQuery query) {
    DB db = mongoTemplate.getDb();/*ww  w  . j a v a2s . c o  m*/
    String tableName = "wx_log" + query.getSuffix();
    DBCollection coll = db.getCollection(tableName);
    BasicDBObject q = new BasicDBObject();
    this.fillQueryCondition(q, query);
    DBCursor cur = coll.find(q);

    List<WxLog> logs = new java.util.concurrent.CopyOnWriteArrayList<WxLog>();

    int limit = query.getPageSize();
    if (limit <= 0) {
        limit = Paging.DEFAULT_PAGE_SIZE;
    }
    if (start < cur.count()) {
        logger.debug("start=" + start);
        logger.debug("limit=" + limit);
        List<DBObject> list = coll.find(q).skip(start).limit(limit).toArray();
        for (DBObject object : list) {
            WxLog log = new WxLog();
            log.setId((Long) object.get("id"));
            log.setIp((String) object.get("ip"));
            log.setActorId((String) object.get("actorId"));
            log.setContent((String) object.get("content"));
            log.setOperate((String) object.get("operate"));
            if (object.containsField("accountId")) {
                log.setAccountId((Long) object.get("accountId"));
            }
            if (object.containsField("openId")) {
                log.setOpenId((String) object.get("openId"));
            }
            if (object.containsField("flag")) {
                log.setFlag((Integer) object.get("flag"));
            }
            if (object.containsField("createTime")) {
                long ts = (Long) object.get("createTime");
                log.setCreateTime(new Date(ts));
            }

            logs.add(log);
        }
    }
    return logs;
}