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.apache.isis.objectstore.nosql.db.mongo.MongoStateReader.java

License:Apache License

public MongoStateReader(final DB db, final ObjectSpecId objectSpecId, final String mongoId) {
    final DBCollection instances = db.getCollection(objectSpecId.asString());
    instance = instances.findOne(mongoId);
    if (instance == null) {
        throw new ObjectNotFoundException(mongoId);
    }//w w  w  .jav  a2  s.  co m
    if (LOG.isDebugEnabled()) {
        LOG.debug("loading " + instance);
    }
}

From source file:org.apache.isis.runtimes.dflt.objectstores.nosql.db.mongo.MongoDb.java

License:Apache License

public void delete(final ObjectSpecId objectSpecId, final String key) {
    final DBCollection instances = db.getCollection(objectSpecId.asString());
    final ObjectId id = new ObjectId(key);
    final DBObject object = instances.findOne(id);
    instances.remove(object);/*from   www. j a v  a 2  s.c o m*/
    LOG.info("removed " + key);
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.replica.GetRootRevisionsCallable.java

License:Apache License

@Override
public Timestamped<RevisionVector> call() throws Exception {
    List<Revision> revisions = new ArrayList<Revision>();
    DBCollection collection = nodeCollections.get(hostName);

    long start = clock.getTime();
    DBObject root = collection.findOne(new BasicDBObject(Document.ID, "0:/"));
    long end = clock.getTime();
    long mid = (start + end) / 2;

    if (root == null) {
        LOG.warn("Can't get the root document on {}", hostName);
        return null;
    }//from  w ww .  j ava2s.  c  o  m

    DBObject lastRev = (DBObject) root.get("_lastRev");
    for (String clusterId : lastRev.keySet()) {
        String rev = (String) lastRev.get(clusterId);
        revisions.add(Revision.fromString(rev));
    }
    LOG.debug("Got /_lastRev from {}: {}", hostName, lastRev);
    return new Timestamped<RevisionVector>(new RevisionVector(revisions), mid);
}

From source file:org.apache.karaf.jaas.modules.mongo.internal.DefaultUserDetailService.java

License:Apache License

@Override
public UserInfo addUser(UserInfo user) throws Exception {

    DB db = getDB();//  w  w w  .  ja v  a 2  s.  com

    DBCollection users = db.getCollection(configuration.getUserCollectionName());

    DBCollection roles = db.getCollection(configuration.getGroupCollectionName());

    DBObject storedUser = users.findOne(new BasicDBObject().append("username", user.getName()));

    if (storedUser == null) {

        users.insert(BasicDBObjectBuilder.start("username", user.getName())
                .append("passwordHash", user.getPassword()).get());

    } else {
        // will not do anything here
    }

    for (String role : user.getGroups()) {

        DBObject roleQuery = new BasicDBObject("name", role);

        // roles are unique by name
        DBObject roleData = roles.findOne(roleQuery, ROLE_PROJECTION);

        if (roleData == null) {
            // add role with user as first member
            BasicDBList members = new BasicDBList();
            members.add(user.getName());
            roleData = BasicDBObjectBuilder.start().add("name", role).add("members", members).get();

            roles.insert(roleData);

        } else {

            // add user to group if not already in the role's member list
            Object mo = roleData.get("members");
            if (mo == null) {

                // TODO what here?
                BasicDBObject updateObject = new BasicDBObject().append("$push",
                        new BasicDBObject("members", user.getName()));

                roles.update(roleQuery, updateObject);

            } else if (mo != null && mo instanceof List) {

                // if user is in group already we dont need to do anything
                List<?> existingMembers = (List<?>) mo;

                if (!existingMembers.contains(user.getName())) {
                    // push this user to the members list
                    BasicDBObject updateObject = new BasicDBObject().append("$push",
                            new BasicDBObject("members", user.getName()));

                    roles.update(roleQuery, updateObject);

                }

            } else {
                log.warn("The members collection of group [{}] is not a list but of type [{}].", role,
                        mo.getClass().getName());
            }

        }

    }

    return user;
}

From source file:org.apache.metamodel.mongodb.mongo2.MongoDbDataContext.java

License:Apache License

@Override
protected Row executePrimaryKeyLookupQuery(Table table, List<SelectItem> selectItems, Column primaryKeyColumn,
        Object keyValue) {//from   ww  w  . j  av  a2s .c om
    final DBCollection collection = _mongoDb.getCollection(table.getName());

    List<FilterItem> whereItems = new ArrayList<FilterItem>();
    SelectItem selectItem = new SelectItem(primaryKeyColumn);
    FilterItem primaryKeyWhereItem = new FilterItem(selectItem, OperatorType.EQUALS_TO, keyValue);
    whereItems.add(primaryKeyWhereItem);
    final DBObject query = createMongoDbQuery(table, whereItems);
    final DBObject resultDBObject = collection.findOne(query);

    DataSetHeader header = new SimpleDataSetHeader(selectItems);

    Row row = MongoDBUtils.toRow(resultDBObject, header);

    return row;
}

From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java

License:Apache License

/**
 * Get a resource//from  w ww  .ja  v a2 s.c om
 */
protected Resource getResource(final ResourceResolver resourceResolver, final String path,
        final String[] info) {
    if (info.length == 0) {
        // special resource : all collections
        return new MongoDBCollectionResource(resourceResolver, path);
    } else if (info.length == 1) {
        // special resource : collection
        if (this.hasCollection(info[0])) {
            return new MongoDBCollectionResource(resourceResolver, path);
        }
        return null;
    }
    logger.debug("Searching {} in {}", info[1], info[0]);
    final DBCollection col = this.getCollection(info[0]);
    if (col != null) {
        final DBObject obj = col.findOne(QueryBuilder.start(getPROP_PATH()).is(info[1]).get());
        logger.debug("Found {}", obj);
        if (obj != null) {
            return new MongoDBResource(resourceResolver, path, info[0], obj, this);
        }
    }

    return null;
}

From source file:org.aw20.mongoworkbench.command.FindOneMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);
    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);/*from w ww.  j  av a2  s .c om*/
    DBObject cmdMap = parseMongoCommandString(db, cmd);

    DBCollection collection = db.getCollection(sColl);

    // Construct the query
    int argSize = ((List) cmdMap.get("findOneArg")).size();

    if (argSize == 1) {
        DBObject ref = (DBObject) ((List) cmdMap.get("findOneArg")).get(0);
        dbo = collection.findOne(ref);
    } else if (argSize >= 2) {
        List findArg = (List) cmdMap.get("findOneArg");
        DBObject ref = (DBObject) findArg.get(0);
        DBObject key = (DBObject) findArg.get(1);
        dbo = collection.findOne(ref, key);
    } else
        throw new Exception("no query specified");

    setMessage("loaded: " + (dbo != null));
}

From source file:org.aw20.mongoworkbench.command.SystemJavaScriptReadCommand.java

License:Open Source License

@Override
public void execute() throws Exception {

    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);
    DB db = mdb.getDB(sDb);//from  w w w . j av  a  2 s. c  o m

    DBCollection coll = db.getCollection("system.js");
    DBObject dbo = coll.findOne(new BasicDBObject("_id", jsName));

    if (dbo.containsField("value")) {
        jsCode = ((Code) dbo.get("value")).getCode();
    }

    setMessage("System JavaScript loaded=" + jsName);
}

From source file:org.chililog.server.data.RepositoryConfigController.java

License:Apache License

/**
 * Tries to retrieve the specified repository by its id. If not found, null is returned.
 * //from w w  w  .j  a va 2s.co  m
 * @param db
 *            mongoDB connection
 * @param id
 *            unique id for the document stored in mongoDB
 * @return <code>RepositoryInfoBO</code> representing the repository or null if repository is not found
 * @throws ChiliLogException
 *             if database or data error
 */
public RepositoryConfigBO tryGet(DB db, ObjectId id) throws ChiliLogException {
    try {
        if (db == null) {
            throw new IllegalArgumentException("db cannot be null");
        }
        if (id == null) {
            throw new IllegalArgumentException("id cannot be null");
        }

        DBCollection coll = db.getCollection(MONGODB_COLLECTION_NAME);
        BasicDBObject condition = new BasicDBObject();
        condition.put(BO.DOCUMENT_ID_FIELD_NAME, id);
        DBObject dbo = coll.findOne(condition);
        if (dbo == null) {
            return null;
        }
        return new RepositoryConfigBO(dbo);
    } catch (MongoException ex) {
        throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage());
    }
}

From source file:org.chililog.server.data.RepositoryConfigController.java

License:Apache License

/**
 * Tries to retrieve the specified repository by its name. If not found, null is returned.
 * /*  w w  w .ja  v  a 2  s .  c  o m*/
 * @param db
 *            mongoDB connection
 * @param name
 *            name of repository to retrieve
 * @return <code>RepositoryInfoBO</code> representing the repository or null if repository is not found
 * @throws ChiliLogException
 *             if database or data error
 */
public RepositoryConfigBO tryGetByName(DB db, String name) throws ChiliLogException {
    try {
        if (db == null) {
            throw new IllegalArgumentException("db cannot be null");
        }
        if (StringUtils.isBlank(name)) {
            throw new IllegalArgumentException("name cannot be blank");
        }

        DBCollection coll = db.getCollection(MONGODB_COLLECTION_NAME);
        BasicDBObject condition = new BasicDBObject();
        condition.put(RepositoryConfigBO.NAME_FIELD_NAME, name);
        DBObject dbo = coll.findOne(condition);
        if (dbo == null) {
            return null;
        }
        return new RepositoryConfigBO(dbo);
    } catch (MongoException ex) {
        throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage());
    }
}