Example usage for com.mongodb BasicDBObject toString

List of usage examples for com.mongodb BasicDBObject toString

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public String toString() 

Source Link

Document

Returns a JSON serialization of this object

The output will look like: {"a":1, "b":["x","y","z"]} }

Usage

From source file:pt.tiago.mongodbteste.MongoDB.java

private void queries() {

    DBCollection coll = db.getCollection("Purchase");
    //find the sum group by category
    DBObject group = new BasicDBObject("$group",
            new BasicDBObject("_id", "$categoryID").append("total", new BasicDBObject("$sum", "$price")));
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("price", 1));
    AggregationOutput output = coll.aggregate(group, sort);
    for (DBObject result : output.results()) {
        System.out.println(result);
    }/*from   ww w . j  av  a2 s.  co  m*/

    System.out.println("////////////////////////////////");

    //find the year of date
    //SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase
    // $group : {_id : { year : {$year : "$birth_date"}},  total : {$sum : 1}
    System.out.println("SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase");
    DBCollection collection2 = db.getCollection("Purchase");
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", new BasicDBObject("year", new BasicDBObject("$year", "$dateOfPurchase")))
                    .append("total", new BasicDBObject("$sum", 1)));
    output = collection2.aggregate(group);
    BasicDBObject basicObj;
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        basicObj = (BasicDBObject) basicObj.get("_id");
        System.out.println(basicObj.get("year"));
        ;

    }

    System.out.println("////////////////////////////////");

    //find the sum with year and categoryID
    // SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ?
    System.out.println(
            "SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ?");
    int year = 2014;
    Calendar cal = Calendar.getInstance();
    cal.set(year, 0, 0);
    Calendar cal2 = Calendar.getInstance();
    cal2.set(year, 11, 31);
    BasicDBObject match = new BasicDBObject("$match",
            new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8")));
    match.put("$match", new BasicDBObject("dateOfPurchase",
            new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime())));
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price")));
    output = coll.aggregate(match, group);
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        System.out.println(basicObj.getDouble("total"));
    }

    System.out.println("////////////////////////////////");

    System.out.println("SELECT SUM(Price) , MONTH(DateOfPurchase)"
            + " FROM Purchase WHERE PersonID = ? AND CategoryID = ? "
            + "AND Price <= ? GROUP BY MONTH(DateOfPurchase)");
    coll = db.getCollection("Purchase");
    BasicDBObject cateObj = new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8"));
    BasicDBObject personObj = new BasicDBObject("personID", new ObjectId("548079fa46e68338719aa1f6"));
    BasicDBList and = new BasicDBList();
    and.add(cateObj);
    and.add(personObj);
    DBObject andCriteria = new BasicDBObject("$and", and);
    DBObject matchCriteria = new BasicDBObject("$match", andCriteria);
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price")));
    group.put("$group",
            new BasicDBObject("_id", new BasicDBObject("month", new BasicDBObject("$month", "$dateOfPurchase")))
                    .append("total", new BasicDBObject("$sum", "$price")));
    output = coll.aggregate(matchCriteria, group);
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        System.out.println(basicObj.toString());
    }

    System.out.println("////////////////////////////////");

    System.out.println("SELECT SUM(Price) , PersonID FROM Purchase WHERE  "
            + "YEAR(DateOfPurchase) = ? AND Price <= ? GROUP BY PersonID");
    coll = db.getCollection("Purchase");
    year = 2014;
    cal = Calendar.getInstance();
    cal.set(year, 0, 0);
    cal2 = Calendar.getInstance();
    cal2.set(year, 11, 31);

    BasicDBObject priceObj = new BasicDBObject("price", new BasicDBObject("$lte", 2000));
    BasicDBObject dateObj = new BasicDBObject("dateOfPurchase",
            new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime()));
    and = new BasicDBList();
    and.add(priceObj);
    and.add(dateObj);
    andCriteria = new BasicDBObject("$and", and);
    matchCriteria = new BasicDBObject("$match", andCriteria);
    group = new BasicDBObject("$group",
            new BasicDBObject("_id", "$personID").append("total", new BasicDBObject("$sum", "$price")));
    output = coll.aggregate(matchCriteria, group);
    for (DBObject result : output.results()) {
        basicObj = (BasicDBObject) result;
        System.out.println(basicObj.toString());
    }

}

From source file:tango.gui.DataManager.java

License:Open Source License

private void extractData() {
    HashMap<MultiKey, TreeSet<String>> newC2CKeys = new HashMap<MultiKey, TreeSet<String>>();
    TreeSet<String> NucKeysToAdd = new TreeSet<String>();
    DBCursor cur = mc.getXPNuclei(xp.getName());
    cur.sort(new BasicDBObject("field_id", 1).append("idx", 1));
    int nbNuc = cur.count();
    IJ.log("extract data nb nuc:" + nbNuc);
    objectMes = new HashMap<Integer, TreeMap<MultiKey3D, String>>(ojectKeys.size());
    nbObjects = new TreeMap<MultiKey2D, int[]>();
    nucTags = new TreeMap<MultiKey2D, Integer>();
    nucIds = new TreeMap<MultiKey2D, String>();
    for (int i : ojectKeys.keySet()) {
        if (i < 0) {
            continue;
        }//from   ww w .  j  ava  2 s  . c o m
        objectMes.put(i, new TreeMap<MultiKey3D, String>());
    }
    if (!ojectKeys.containsKey(0)) {
        objectMes.put(0, new TreeMap<MultiKey3D, String>());
        ojectKeys.put(0, new TreeSet<String>());
    }
    o2oMes = new HashMap<MultiKey, TreeMap<MultiKey4D, String>>();
    for (MultiKey dk : c2cKeys.keySet()) {
        o2oMes.put(dk, new TreeMap<MultiKey4D, String>());
        newC2CKeys.put(dk, new TreeSet<String>());
    }
    while (cur.hasNext()) {
        BasicDBObject nuc = (BasicDBObject) cur.next();
        if (nuc.getInt("tag", 0) < 0) {
            continue; // exclude negative tags
        }
        ObjectId nucId = (ObjectId) nuc.get("_id");
        int nucIdx = nuc.getInt("idx");
        String fieldName = mc.getField((ObjectId) nuc.get("field_id")).getString("name");
        int[] nbPart = new int[channelNames.length];
        //mesure objects
        for (int i = 0; i < channelNames.length; i++) {
            TreeMap<MultiKey3D, String> omes = objectMes.get(i);
            TreeSet<String> keys = ojectKeys.get(i);
            DBCursor cursor = mc.getObjectsCursor(nucId, i);
            cursor.sort(new BasicDBObject("idx", 1));
            nbPart[i] = cursor.count();
            if (keys != null && !keys.isEmpty()) {
                while (cursor.hasNext()) {
                    BasicDBObject o = (BasicDBObject) cursor.next();
                    //IJ.log("o="+o);
                    //IJ.log("omes="+omes);
                    //IJ.log("f="+fieldName+" "+nucIdx+" "+o.getInt("idx")+" "+keys);
                    for (String k : keys) {
                        //IJ.log("k="+k+" "+o.getString(k));
                        if (o.getString(k) != null) {
                            omes.put(new MultiKey3D(fieldName, nucIdx, o.getInt("idx"), k),
                                    o.get(k).toString());
                        }
                    }
                }
            }
            cursor.close();
        }
        String s = "";
        for (int i : nbPart) {
            s += i + ";";
        }
        //IJ.log("nb objects:" + s);
        MultiKey2D k2D = new MultiKey2D(fieldName, nucIdx, "nbParts");
        nbObjects.put(k2D, nbPart);
        nucTags.put(k2D, nuc.getInt("tag", 0));
        nucIds.put(k2D, nuc.getString("_id"));
        //C2C
        TreeMap<MultiKey3D, String> nucMes = objectMes.get(0);
        for (MultiKey dk : c2cKeys.keySet()) {
            if (dk.getKey(0) < 0) {
                continue;
            }
            int size = (dk.getKey(0) != dk.getKey(1)) ? nbPart[dk.getKey(0)] * nbPart[dk.getKey(1)]
                    : nbPart[dk.getKey(0)] * (nbPart[dk.getKey(0)] - 1) / 2;
            BasicDBObject mes = mc.getMeasurementStructure(nucId, dk.getKeys(), true);
            //IJ.log("get mes:" + dk + " mes");
            TreeMap<MultiKey4D, String> o2oMesDk = o2oMes.get(dk);
            TreeSet<String> keys = c2cKeys.get(dk);
            TreeSet<String> newKeys = newC2CKeys.get(dk);

            for (String k : keys) {
                Object o = mes.get(k);
                if (o instanceof BasicDBList) {
                    BasicDBList list = ((BasicDBList) o);
                    if (list.size() == size) {
                        int count = 0;
                        if (dk.getKey(0) != dk.getKey(1)) {
                            for (int p1 = 1; p1 <= nbPart[dk.getKey(0)]; p1++) {
                                for (int p2 = 1; p2 <= nbPart[dk.getKey(1)]; p2++) {
                                    o2oMesDk.put(new MultiKey4D(fieldName, nucIdx, p1, p2, k),
                                            list.get(count).toString());
                                    count++;
                                }
                            }
                        } else {
                            for (int p1 = 1; p1 < nbPart[dk.getKey(0)]; p1++) {
                                for (int p2 = p1 + 1; p2 <= nbPart[dk.getKey(1)]; p2++) {
                                    o2oMesDk.put(new MultiKey4D(fieldName, nucIdx, p1, p2, k),
                                            list.get(count).toString());
                                    count++;

                                }
                            }
                        }
                        newKeys.add(k);
                    }
                } else if (o instanceof Number || o instanceof String) {
                    String newKey = channelNames[dk.getKey(0)] + "." + channelNames[dk.getKey(1)] + "." + k;
                    nucMes.put(new MultiKey3D(fieldName, nucIdx, 1, newKey), o.toString());
                    NucKeysToAdd.add(newKey);
                }
            }
        }
    }
    cur.close();
    this.ojectKeys.get(0).addAll(NucKeysToAdd);
    this.c2cKeys = newC2CKeys;
}

From source file:tango.mongo.MongoConnector.java

License:Open Source License

public synchronized void removeNucleusImage(ObjectId nucleus_id, int fileIdx, int fileType) {
    BasicDBObject query = new BasicDBObject("nucleus_id", nucleus_id).append("fileIdx", fileIdx)
            .append("fileType", fileType);
    System.out.println("removing nucleus image: " + query.toString());

    gfsNucleus.remove(query); // TODO BUG NE REMOVE PLUS!
}

From source file:tango.mongo.MongoConnector.java

License:Open Source License

public synchronized ImageHandler getNucImage(ObjectId cellId, int fileIdx, int fileType) {
    BasicDBObject query = new BasicDBObject("nucleus_id", cellId).append("fileIdx", fileIdx).append("fileType",
            fileType);/*from   ww w.j ava  2s.  co m*/
    GridFSDBFile f = this.gfsNucleus.findOne(query);
    System.out.println("get nucleus image: " + query.toString() + " found? " + (f != null));
    if (f != null) {
        return createImage(f);
    }
    return null;
}

From source file:tango.util.ProcessingChainsToText.java

public ProcessingChainsToText(BasicDBObject chain) {
    if (chain != null) {
        json = new JSONObject(chain.toString());
    }
}

From source file:uk.ac.soton.itinnovation.sad.service.helpers.PluginsHelper.java

License:Open Source License

/**
 * Use to start searching only input data for the job.
 *
 * @return database object with job IDs/plugin names selected.
 *//*from www.  ja  v  a 2 s  .  c  om*/
public BasicDBObject getInputDataQuery() {
    BasicDBObject searchQuery = new BasicDBObject();

    // Only search in input data for this job
    ObjectId[] jobIds = getInputJobIdsAsObjectIds();
    String[] pluginNames = getInputPluginNamesAsStringArray();
    BasicDBList or = new BasicDBList();
    or.add(new BasicDBObject("pluginName", new BasicDBObject("$in", pluginNames)));
    or.add(new BasicDBObject("SADJobID", new BasicDBObject("$in", jobIds)));
    searchQuery.append("$or", or);

    logger.debug("Returning query based on input data: " + searchQuery.toString());

    return searchQuery;
}

From source file:uk.co.revsys.oddball.rules.MongoDBHelper.java

private BasicDBObject buildQuery(String owner, String queryString, Map<String, String> options)
        throws IOException, InvalidTimePeriodException {
    if (queryString == null) {
        queryString = "{ }";
    }//from w  ww.  j  a va2s  . c  om
    if (options.get("binQuery") != null) {
        queryString = addBinQuery(queryString, options.get("binQuery"));
    }
    BasicDBObject query = new BasicDBObject(JSONUtil.json2map(queryString));
    if (!owner.equals(Oddball.ALL)) {
        String ownerProperty = OWNERPROPERTY;
        if (options.containsKey("ownerProperty")) {
            ownerProperty = options.get("ownerProperty");
        }
        query.append("case." + ownerProperty, owner);
    }
    if (options.get("recent") != null) {
        addRecentQuery(query, options.get("recent"));
    }
    if (options.get("ago") != null) {
        addAgoQuery(query, options.get("ago"));
    }
    if (options.get("since") != null) {
        addSinceQuery(query, options.get("since"));
    }
    if (options.get("before") != null) {
        addBeforeQuery(query, options.get("before"));
    }
    if (options.get("caseRecent") != null) {
        addCaseRecentQuery(query, options.get("caseRecent"));
    }
    if (options.get("caseAgo") != null) {
        addCaseAgoQuery(query, options.get("caseAgo"));
    }
    if (options.get("caseSince") != null) {
        addCaseSinceQuery(query, options.get("caseSince"));
    }
    if (options.get("caseBefore") != null) {
        addCaseBeforeQuery(query, options.get("caseBefore"));
    }
    if (options.get("forEach") != null) {
        addForEachQuery(query, options.get("forEach"), options.get("forEachValue"));
    }
    if (options.get("series") != null) {
        addSeriesQuery(query, options.get("series"));
    }
    if (options.get("agent") != null) {
        addAgentQuery(query, options.get("agent"));
    }
    if (options.get("sessionId") != null) {
        addSessionIdQuery(query, options.get("sessionId"));
    }
    if (options.get("userId") != null) {
        addUserIdQuery(query, options.get("userId"));
    }
    System.out.println("Query=" + query.toString());
    return query;
}

From source file:yelpapp.HW3.java

private String queryCategoryQuery(ArrayList<String> str) {
    BasicDBObject inQuery = new BasicDBObject();
    BasicDBObject fields = new BasicDBObject();
    fields.put("business_id", 1);
    fields.put("name", 1);
    fields.put("state", 1);
    fields.put("city", 1);
    fields.put("stars", 1);
    fields.put("_id", 0);

    inQuery.put("categories", new BasicDBObject("$in", str));
    return inQuery.toString();
}

From source file:yelpapp.HW3.java

private String proxqueryonly(Double longitude, Double latitude, Integer miles) {
    BasicDBObject coordinates = new BasicDBObject("coordinates", asList(longitude, latitude));
    BasicDBObject type = new BasicDBObject("type", "Point").append("coordinates", asList(longitude, latitude));
    BasicDBObject geometry = new BasicDBObject("$geometry", type);
    System.out.println(geometry);
    double maxdistancekeyenin = 1609.34 * miles;
    BasicDBObject maxdistane = new BasicDBObject("$maxDistance", maxdistancekeyenin);
    BasicDBObject near = new BasicDBObject("$near", geometry.append("$maxDistance", maxdistancekeyenin));

    BasicDBObject location = new BasicDBObject("loc", near);
    String Query = location.toString();
    return Query;
}