Example usage for com.mongodb DBCursor count

List of usage examples for com.mongodb DBCursor count

Introduction

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

Prototype

public int count() 

Source Link

Document

Counts the number of objects matching the query.

Usage

From source file:com.cedac.security.acls.mongo.MongoAclService.java

License:Apache License

@Override
public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
    LOG.debug(ACL, "Looking for children of object identity {}", parentIdentity);

    DBObject query = queryByParentIdentity(parentIdentity);
    DBObject projection = new BasicDBObject(objectIdFieldName, true);
    DBCursor cursor = null;
    try {//w  w w  .ja  v a 2  s.c  om
        cursor = getAclCollection().find(query, projection);
        if (cursor.count() == 0) {
            LOG.debug(ACL, "No child object found for identity {}", parentIdentity);

            return null;
        }

        LOG.trace(ACL, "Streaming cursor in order to retrieve child object identities");

        List<ObjectIdentity> oids = new ArrayList<ObjectIdentity>();
        while (cursor.hasNext()) {
            oids.add(toObjectIdentity((DBObject) cursor.next().get(objectIdFieldName)));
        }
        return oids;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.cedac.security.oauth2.provider.token.store.MongoTokenStore.java

License:Apache License

public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
    List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();

    DBObject query = new BasicDBObject(clientIdFieldName, clientId);
    DBObject projection = new BasicDBObject(tokenFieldName, 1);
    DBCursor cursor = null;
    try {/*from   w ww  .j  a  v a2  s . c  o m*/
        cursor = getAccessTokenCollection().find(query, projection);
        if (cursor.count() > 0) {
            while (cursor.hasNext()) {
                OAuth2AccessToken token = mapAccessToken(cursor.next());
                if (token != null) {
                    accessTokens.add(token);
                }
            }
        } else {
            LOG.info("Failed to find access token for clientId {}", clientId);
        }
        return accessTokens;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.cedac.security.oauth2.provider.token.store.MongoTokenStore.java

License:Apache License

public Collection<OAuth2AccessToken> findTokensByUserName(String userName) {
    List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();

    DBObject query = new BasicDBObject(usernameFieldName, userName);
    DBObject projection = new BasicDBObject(tokenFieldName, 1);
    DBCursor cursor = null;
    try {//w  w  w . j a  va2 s  . co  m
        cursor = getAccessTokenCollection().find(query, projection);
        if (cursor.count() > 0) {
            while (cursor.hasNext()) {
                OAuth2AccessToken token = mapAccessToken(cursor.next());
                if (token != null) {
                    accessTokens.add(token);
                }
            }
        } else {
            LOG.info("Failed to find access token for username {}.", userName);
        }
        return accessTokens;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.cedac.security.oauth2.provider.token.store.MongoTokenStore.java

License:Apache License

public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
    List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();

    DBObject query = new BasicDBObject(clientIdFieldName, clientId).append(usernameFieldName, userName);
    DBObject projection = new BasicDBObject(tokenFieldName, 1);
    DBCursor cursor = null;
    try {/*from w  ww.j  a v a2 s . c  om*/
        cursor = getAccessTokenCollection().find(query, projection);
        if (cursor.count() > 0) {
            while (cursor.hasNext()) {
                OAuth2AccessToken token = mapAccessToken(cursor.next());
                if (token != null) {
                    accessTokens.add(token);
                }
            }
        } else {
            LOG.info("Failed to find access token for clientId {} and username {}.", clientId, userName);
        }
        return accessTokens;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.clavain.workers.DataRetentionWorker.java

License:Apache License

@Override
public void run() {
    int month = 2629743;
    logger.info("Started DataRetentionWorker");
    try {/*from w w  w  .j a v a 2  s.c o m*/
        int sleepTime = Integer.parseInt(p.getProperty("dataretention.period")) * 3600000;
        while (true) {
            Thread.sleep(sleepTime);
            logger.info("[DataRetentionWorker] Starting Retention Run");
            Connection conn = connectToDatabase(p);
            java.sql.Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE retention > 0 AND userrole != 'user'");
            while (rs.next()) {
                logger.info("[DataRetentionWorker - User Mode] Processing User: " + rs.getString("username"));
                // get nodes from this user
                Iterator it = v_munin_nodes.iterator();
                List l_nodes = new ArrayList();
                while (it.hasNext()) {
                    MuninNode l_mn = (MuninNode) it.next();
                    if (l_mn.getUser_id().equals(rs.getInt("id"))) {
                        logger.info("[DataRetentionWorker User Mode] probing " + l_mn.getHostname()
                                + " from user: " + rs.getString("username"));
                        String colname = l_mn.getUser_id() + "_" + l_mn.getNode_id(); // recv
                        String colnamees = l_mn.getNode_id() + "_ess"; // time
                        int matchtime = rs.getInt("retention") * month;
                        matchtime = getUnixtime() - matchtime;
                        BasicDBObject query = new BasicDBObject("recv", new BasicDBObject("$lt", matchtime));
                        String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
                        db = m.getDB(dbName);
                        col = db.getCollection(colname);
                        DBCursor cursor = col.find(query);
                        if (cursor.count() > 0) {
                            logger.info("[DataRetentionWorker User Mode] result for " + l_mn.getHostname()
                                    + " from user: " + rs.getString("username") + " affected for deletion: "
                                    + cursor.count() + " matchtime: lt " + matchtime);
                        }
                        col.remove(query);

                        // now ESSENTIALS
                        query = new BasicDBObject("time", new BasicDBObject("$lt", matchtime));
                        dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbessentials");
                        db = m.getDB(dbName);
                        col = db.getCollection(colnamees);
                        cursor = col.find(query);
                        if (cursor.count() > 0) {
                            logger.info("[DataRetentionWorker User Mode] ESSENTIAL result for "
                                    + l_mn.getHostname() + " from user: " + rs.getString("username")
                                    + " affected for deletion: " + cursor.count() + " matchtime: lt "
                                    + matchtime);
                        }
                        col.remove(query);

                    }
                }
            }
            //conn.close();

            logger.info("[DataRetentionWorker User Mode] Finished Retention Run");

            logger.info("[DataRetentionWorker Custom Mode] Starting Retention Run");
            stmt = conn.createStatement();
            rs.close();
            rs = stmt.executeQuery("SELECT * FROM plugins_custom_interval WHERE retention > 0");
            while (rs.next()) {
                logger.info("[DataRetentionWorker - Custom Mode] Processing Custom ID: " + rs.getString("id")
                        + " Node: " + rs.getString("node_id") + " Plugin: " + rs.getString("pluginname"));
                MuninNode l_mn = getMuninNode(rs.getInt("node_id"));
                if (l_mn != null) {
                    String colname = l_mn.getUser_id() + "_" + l_mn.getNode_id(); // recv
                    int matchtime = rs.getInt("retention") * 86400;
                    matchtime = getUnixtime() - matchtime;
                    BasicDBObject query = new BasicDBObject("recv", new BasicDBObject("$lt", matchtime));
                    query.append("customId", rs.getInt("id"));
                    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
                    db = m.getDB(dbName);
                    col = db.getCollection(colname);
                    DBCursor cursor = col.find(query);
                    if (cursor.count() > 0) {
                        logger.info("[DataRetentionWorker Custom Mode] Custom Interval (CID: " + rs.getInt("id")
                                + ") POSITIVE RESULTS for " + l_mn.getHostname() + " affected for deletion: "
                                + cursor.count() + " collection: " + colname + " matchtime: lt " + matchtime);
                    } else {
                        logger.info("[DataRetentionWorker Custom Mode] Custom Interval (CID: " + rs.getInt("id")
                                + ") NEGATIVE RESULTS for " + l_mn.getHostname() + "count:  " + cursor.count()
                                + " collection: " + colname + " matchtime: lt " + matchtime);
                    }
                    col.remove(query);

                } else {
                    logger.warn("[DataRetentionWorker Custom Mode] getMuninNode returned null for node_id "
                            + rs.getInt("node_id"));
                }
            }
            logger.info("[DataRetentionWorker Custom Mode] Finished Retention Run");

            // Service Checks
            logger.info("[DataRetentionWorker ServiceCheck Mode] Starting Retention Run");
            stmt = conn.createStatement();
            rs.close();
            rs = stmt.executeQuery(
                    "SELECT service_checks.*,users.retention,users.username FROM service_checks LEFT JOIN users on service_checks.user_id = users.id WHERE users.retention > 0");
            while (rs.next()) {
                logger.info("[DataRetentionWorker - ServiceCheck Mode] Processing ServiceCheck ID: "
                        + rs.getString("id") + " Name: " + rs.getString("check_name") + " for User: "
                        + rs.getString("username") + " Retention: " + rs.getString("retention"));

                String colname = rs.getInt("user_id") + "cid" + rs.getInt("id");
                int matchtime = rs.getInt("retention") * month;
                matchtime = getUnixtime() - matchtime;
                BasicDBObject query = new BasicDBObject("time", new BasicDBObject("$lt", matchtime));
                query.append("cid", rs.getInt("id"));
                query.append("status", 0);
                String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbchecks");
                db = m.getDB(dbName);
                col = db.getCollection(colname);
                DBCursor cursor = col.find(query);
                if (cursor.count() > 0) {
                    logger.info("[DataRetentionWorker ServiceCheck Mode] ServiceCheck ID: " + rs.getString("id")
                            + " Name: " + rs.getString("check_name") + " for User: " + rs.getString("username")
                            + " affected for deletion: " + cursor.count() + " matchtime: lt " + matchtime);
                }
                col.remove(query);

            }
            logger.info("[DataRetentionWorker ServiceCheck Mode] Finished Retention Run");
            conn.close();
        }

    } catch (Exception ex) {
        logger.error("Error in DataRetentionWorker: " + ex.getLocalizedMessage());
    }
}

From source file:com.cyslab.craftvm.rest.mongo.AggregateServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//from   w  w w.  ja v a 2s. c  o  m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null, sort = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }
        // sort param
        data = r.readLine();
        if (data != null) {
            try {
                sort = (DBObject) JSON.parse(data);
            } catch (JSONParseException e) {
                error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg"));
                return;
            }
        }

    } finally {
        if (r != null)
            r.close();
    }

    DBCursor c;
    if (sort == null)
        c = col.find(q);
    else
        c = col.find(q).sort(sort);
    if (c == null) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

From source file:com.cyslab.craftvm.rest.mongo.AggregateServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from   w  w  w.  j a v  a 2s .c o  m*/
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    DBCursor c = col.find();
    if (c == null) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

From source file:com.cyslab.craftvm.rest.mongo.QueryServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    // server auth
    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//from  w  w  w.  j  a v a2s. c om
        return;
    }

    String ret = null;

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    String _fields = req.getParameter("fields");
    String fields[] = null;
    if (_fields != null)
        fields = _fields.split("[,]");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    BufferedReader r = null;
    DBObject q = null, sort = null;

    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
            if (cache != null) {
                buf.append(db_name);
                buf.append(col_name);
                buf.append(data);
            }
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }
        // sort param
        data = r.readLine();
        if (data != null) {
            try {
                sort = (DBObject) JSON.parse(data);
            } catch (JSONParseException e) {
                error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg"));
                return;
            }
            if (cache != null)
                buf.append(data);
        }

    } finally {
        if (r != null)
            r.close();
    }

    // limit
    int lim;
    if (limit != null) {
        try {
            lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN);
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            return;
        }
    } else {
        lim = MAX_FIELDS_TO_RETURN;
    }
    if (cache != null) {
        buf.append(";limit=");
        buf.append(lim);
    }

    // skip
    int sk = -1;
    if (skip != null) {
        try {
            sk = Integer.parseInt(skip);
            if (cache != null) {
                buf.append(";skip=");
                buf.append(sk);
            }
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            return;
        }
    }

    // fields
    if (cache != null && _fields != null) {
        buf.append(";fields=");
        buf.append(_fields);
    }

    // from cache
    String cache_key = null;
    if (cache != null) {
        cache_key = buf.toString();
        try {
            ret = (String) cache.get(cache_key);
        }
        // some wrong char in key
        catch (IllegalArgumentException e) {
            int l = buf.length();
            for (int i = 0; i < l; i++) {
                if (buf.charAt(i) == ' ')
                    buf.setCharAt(i, '*');
            }
            cache_key = buf.toString();
            ret = (String) cache.get(cache_key);
        }
        if (ret != null) {
            out_str(req, ret, "application/json");
            return;
        }
    }

    // cursor
    DBCursor c;
    if (fields != null) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        int len = fields.length;
        for (int i = 0; i < len; i++) {
            String s = fields[i];
            sb.append('"');
            sb.append(s);
            sb.append('"');
            sb.append(":1");
            if (i != (len - 1))
                sb.append(",");
        }
        sb.append("}");
        c = col.find(q, (DBObject) JSON.parse(sb.toString()));
    } else
        c = col.find(q);

    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    if (sort != null)
        c.sort(sort);

    res.setIntHeader("X-Documents-Count", c.count());

    c.limit(lim);
    if (sk != -1)
        c.skip(sk);

    // reset buf
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    ret = buf.toString();
    if (cache != null)
        cache.set(cache_key, ret);

    out_str(req, ret, "application/json");

}

From source file:com.cyslab.craftvm.rest.mongo.QueryServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*  w  w w. j a va  2  s .  c o m*/
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    DBCursor c = col.find();
    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doDelete()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from  ww w  . jav a2s . c  o m*/
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    // search
    if (do_search) {

        DBCursor c = col.find(q);
        long l = c.count();
        String todelete[] = new String[(int) l];
        int n = 0;

        while (c.hasNext()) {

            DBObject o = c.next();
            ObjectId oid = (ObjectId) o.get("_id");
            String id = oid.toStringMongod();
            todelete[n++] = id;

        }
        c.close();
        search.get_writer().delete(todelete);

    }

    WriteResult wr = col.remove(q, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_OK);

}