Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

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

Prototype

@Nullable
public DBObject findOne(final Object id) 

Source Link

Document

Get a single document from collection by '_id'.

Usage

From source file:org.i3xx.step.clockmongo.service.impl.ClockPersistenceServiceImpl.java

License:Apache License

/**
 * @param nspc The namespace//from w w w .  ja  v  a2  s .c om
 * @param symbol The symbol
 * @return The time statement
 */
public String getMapping(String nspc, String symbol) {
    logger.trace("Retrieves the object nspc:{}, symbol:{}", nspc, symbol);

    DBCollection col = ensureCollection(nspc, symbol);
    DBObject dbo = col.findOne(symbolQuery(symbol));

    if (dbo == null) {
        return null;
    }

    return (String) dbo.get("statement");
}

From source file:org.i3xx.step.clockmongo.service.impl.ClockPersistenceServiceImpl.java

License:Apache License

/**
 * @param col The collection to get the object from
 * @param symbol The symbol (key)// www . j a v a  2 s  .co  m
 * @param timeout The timeout or -1 for no timeout
 * @return The DBObject
 */
private DBObject ensureObject(DBCollection col, String symbol) {
    DBObject dbo = null;
    DBObject query = new BasicDBObject("symbol", symbol);
    dbo = col.findOne(query);

    if (dbo == null) {
        String nspc = col.getName();

        dbo = new BasicDBObject();
        dbo.put("nspc", nspc);
        dbo.put("symbol", symbol);
        dbo.put("born", new Long(System.currentTimeMillis()));
        dbo.put("statement", "");

        col.insert(dbo);
    }

    return dbo;
}

From source file:org.mandar.analysis.recsys2014.recsysMain.java

License:Open Source License

public void run() {
    // We first need to configure the data access.
    LenskitConfiguration dataConfig = this.configureDAO(DBSettings.TRAINING_COLLECTION);
    // Now we create the LensKit configuration...
    LenskitConfiguration config = new LenskitConfiguration();
    if (algo.equals("svd")) {
        config = this.configureSVDRecommender(numFeatures, numIterations, regularizationParam,
                stoppingCondition, threshold);
    } else if (algo.equals("ii")) {
        config = this.configureIIRecommender(numNeighbours, similarityModel);
    } else if (algo.equals("uu")) {
        config = this.configureUURecommender(numNeighbours);
    } else if (algo.equals("so")) {
        config = this.configureSORecommender(damping);
    } else if (algo.equals("tfidf")) {
        config = this.configureTFIDFRecommender();
    }//from   w  w w  . j  a  v  a2  s  .co  m

    // There are more parameters, roles, and components that can be set. See the
    // JavaDoc for each recommender algorithm for more information.
    // Now that we have a factory, build a recommender from the configuration
    // and data source. This will compute the similarity matrix and return a recommender
    // that uses it.
    LenskitRecommender rec = null;
    try {
        LenskitRecommenderEngine engine = LenskitRecommenderEngine.newBuilder().addConfiguration(config)
                .addConfiguration(dataConfig).build();
        rec = engine.createRecommender(dataConfig);

    } catch (RecommenderBuildException e) {
        e.printStackTrace();
        System.exit(1);
    }
    // we want to recommend items
    if ("training".equals(this.goal)) {
        ItemRecommender irec = rec.getItemRecommender();
        assert irec != null; // not null because we configured one
        // for users
        try {
            MongoClient mongoClient = new MongoClient(DBSettings.DBHOST);
            DB db = mongoClient.getDB(DBSettings.DATABASE);
            DBCollection collection = db.getCollection(DBSettings.MOVIES_COLLECTION);
            for (long user : users) {
                // get 10 recommendation for the user
                List<ScoredId> recs = irec.recommend(user, 10);
                System.out.format("Recommendations for %d:\n", user);
                for (ScoredId item : recs) {
                    DBObject obj = collection.findOne(new BasicDBObject(DBSettings.FIELDS.movie, item.getId()));
                    String recTitle = obj.get("title").toString();
                    String recDirector = obj.get("director").toString();
                    String recRel = obj.get("release_date").toString();
                    String recStars = obj.get("stars").toString();

                    System.out.format("\tID:%d, %s, %s Directed By: %s Starring: %s\n", item.getId(), recTitle,
                            recRel, recDirector, recStars);
                }
            }
            mongoClient.close();
        } catch (UnknownHostException u) {
            u.printStackTrace();
        }
    } else if ("eval".equals(this.goal)) {
        //ItemScorer iscorer = rec.getItemScorer();
        RatingPredictor rat = rec.getRatingPredictor();
        File outFile = new File("data/participant_solution_" + algo + ".dat");
        String line = "";
        //String cvsSplitBy = ",";
        long eng = 0;
        int count = 0;
        try {
            long lines = Utils.countLines("data/test_solution.dat");
            //outFile.delete();
            BufferedWriter brout = new BufferedWriter((new FileWriter(outFile, false)));
            //BufferedReader br = new BufferedReader(new FileReader(csvData));
            long progress = 0;
            //br.readLine();
            System.out.println(
                    "Reading from Test Set and writing result " + "data/participant_solution_" + algo + ".dat");

            MongoClient mongoClient = new MongoClient(DBSettings.DBHOST);
            DB db = mongoClient.getDB(DBSettings.DATABASE);
            DBCollection collection = db.getCollection(DBSettings.TEST_COLLECTION_EMPTY);
            DBCursor cur = collection.find();

            ArrayList<DBObject> arr = new ArrayList<DBObject>(cur.size());

            System.out.println("Making ObjectArrayList out of test collection result");
            while (cur.hasNext()) {
                DBObject buff = cur.next();
                eng = (long) Math.abs(rat.predict(Long.parseLong(buff.get("uID").toString()),
                        Long.parseLong(buff.get("movieID").toString())));
                buff.put("engagement", eng);
                arr.add(buff);
                count++;
            }

            cur.close();
            //Now sort this by uID (desc), engagement (desc) and tweetID (desc)
            System.out.println("Sorting ObjectArrayList");
            Collections.sort(arr, new MongoComparator());
            for (int i = 0; i < arr.size(); i++) {
                brout.write(arr.get(i).get("uID") + "," + arr.get(i).get("tweetID") + ","
                        + arr.get(i).get("engagement"));
                brout.newLine();
                progress++;
                if ((progress * 100 / lines) % 10 >= 0 && (progress * 100 / lines) % 10 <= 1) {
                    System.out.println("File write Progress: " + (progress * 100 / lines) + " %");
                }
            }
            brout.close();

            ProcessBuilder pbr = new ProcessBuilder("java", "-jar",
                    "rscevaluator-0.1-jar-with-dependencies.jar", "data/test_solution.dat",
                    "data/participant_solution_" + algo + ".dat");
            Process p = pbr.start();

            BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
            double resultbuff = 0.0d;
            while ((line = is.readLine()) != null) {
                if (line.contains("nDCG@10:")) {
                    resultbuff = Double.parseDouble(line.substring(9));
                }
                System.out.println(line);
            }
            System.out.println("Writing evaluation results to MongoDB");
            this.writeAlgoTestResults(resultbuff, db);
            mongoClient.close();
            p.waitFor();

        } catch (FileNotFoundException f) {
            f.printStackTrace();
        } catch (IOException f) {
            f.printStackTrace();
        } catch (InterruptedException i) {
            i.printStackTrace();
        } catch (NullPointerException n) {
            n.printStackTrace();
        }
    }
}

From source file:org.mobicents.servlet.sip.restcomm.dao.mongodb.MongoAccountsDao.java

License:Open Source License

private Account getAccount(final DBCollection collection, final Sid sid) {
    final BasicDBObject query = new BasicDBObject();
    query.put("sid", sid.toString());
    final DBObject result = collection.findOne(query);
    if (result != null) {
        return toAccount(result);
    } else {/*  w ww  . j a  v a  2  s  .  c  om*/
        return null;
    }
}

From source file:org.modeshape.jcr.value.binary.MongodbBinaryStore.java

License:Apache License

/**
 * Modifies content header.//from www  .  j  a  va2s  .c o  m
 * 
 * @param content stored content
 * @param fieldName attribute name
 * @param value new value for the attribute
 */
private void setAttribute(DBCollection content, String fieldName, Object value) {
    DBObject header = content.findOne(HEADER);
    BasicDBObject newHeader = new BasicDBObject();

    // clone header
    newHeader.put(FIELD_CHUNK_TYPE, header.get(FIELD_CHUNK_TYPE));
    newHeader.put(FIELD_MIME_TYPE, header.get(FIELD_MIME_TYPE));
    newHeader.put(FIELD_EXTRACTED_TEXT, header.get(FIELD_EXTRACTED_TEXT));
    newHeader.put(FIELD_UNUSED, header.get(FIELD_UNUSED));
    newHeader.put(FIELD_UNUSED_SINCE, header.get(FIELD_UNUSED_SINCE));

    // modify specified field and update record
    newHeader.put(fieldName, value);
    content.update(HEADER, newHeader);
}

From source file:org.modeshape.jcr.value.binary.MongodbBinaryStore.java

License:Apache License

/**
 * Gets attribute's value./*from w  w w.  j a va  2s . c  om*/
 * 
 * @param content stored content
 * @param fieldName attribute name
 * @return attributes value
 */
private Object getAttribute(DBCollection content, String fieldName) {
    return content.findOne(HEADER).get(fieldName);
}

From source file:org.mongoj.samples.service.persistence.CarPersistenceImpl.java

License:Open Source License

public Car fetchByPrimaryKey(Serializable primaryKey) throws SystemException {
    DBCollection collection = getDB().getCollection(CarImpl.COLLECTION_NAME);

    DBObject criteria = new QueryBuilder().put("_id").is(new ObjectId(primaryKey.toString())).get();

    DBObject dbObject = collection.findOne(criteria);

    return getDocument(dbObject);
}

From source file:org.mongoj.samples.service.persistence.CarPersistenceImpl.java

License:Open Source License

public Car findByVIN(String vIN) throws SystemException {
    String[] searchFields = { "VIN" };

    DBCollection collection = getDB().getCollection(CarImpl.COLLECTION_NAME);

    int i = 0;//w ww  . jav a 2s  .  c o m

    DBObject criteria = new QueryBuilder().put(searchFields[i++]).is(vIN).get();

    DBObject dbObject = collection.findOne(criteria);

    return getDocument(dbObject);
}

From source file:org.mongoj.samples.service.persistence.UserPersistenceImpl.java

License:Open Source License

public User fetchByPrimaryKey(Serializable primaryKey) throws SystemException {
    DBCollection collection = getDB().getCollection(UserImpl.COLLECTION_NAME);

    DBObject criteria = new QueryBuilder().put("_id").is(new ObjectId(primaryKey.toString())).get();

    DBObject dbObject = collection.findOne(criteria);

    return getDocument(dbObject);
}

From source file:org.mongoj.samples.service.persistence.UserPersistenceImpl.java

License:Open Source License

public User findByUserId(long userId) throws SystemException {
    String[] searchFields = { "userId" };

    DBCollection collection = getDB().getCollection(UserImpl.COLLECTION_NAME);

    int i = 0;/*from   w  w  w.j  a  va2s.  com*/

    DBObject criteria = new QueryBuilder().put(searchFields[i++]).is(userId).get();

    DBObject dbObject = collection.findOne(criteria);

    return getDocument(dbObject);
}