List of usage examples for com.mongodb DBCollection findOne
@Nullable
public DBObject findOne()
From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java
/** * /* ww w . j a va2 s. co m*/ * @return */ public ArrayList<String> getMelwinAdmin() { ArrayList<String> melwinAdmin = new ArrayList<>(); DBCollection dbCollectionAdmin = db.getCollection("admin"); DBObject admin = dbCollectionAdmin.findOne(); melwinAdmin.add((String) admin.get("melwinID")); melwinAdmin.add((String) admin.get("melwinKey")); return melwinAdmin; }
From source file:no.nlf.avvik.melwinSOAPconnection.MongoOperations.java
/** * Saves a single Parachuteobject to mongoDB * /*from w ww. j a v a2s . c o m*/ * @param parachutist */ public void addJumperToDb(Parachutist parachutist) { DBCollection dbCollectionParachutistsCount = db.getCollection("jumpercounter"); DBCollection dbCollectionParachutists = db.getCollection("jumpers"); BasicDBObject incrementJumpcount = new BasicDBObject().append("$inc", new BasicDBObject().append("seq", 1)); BasicDBObject query = new BasicDBObject("_id", "jumperCount"); int countInt = (int) dbCollectionParachutistsCount.findOne().get("seq"); ArrayList<Integer> memberLicenses = new ArrayList<>(); for (License license : parachutist.getLicenses()) { memberLicenses.add(license.getId()); } ArrayList<Integer> memberClubs = new ArrayList<>(); for (Club club : parachutist.getMemberclubs()) { memberClubs.add(club.getId()); } dbCollectionParachutistsCount.update(query, incrementJumpcount); BasicDBObject parachutistMongoObject = new BasicDBObject("melwinId", parachutist.getMelwinId()) .append("_class", "no.nlf.models.mongoclasses.MongoParachutist").append("memberclubs", memberClubs) .append("licenses", memberLicenses).append("firstname", parachutist.getFirstname()) .append("lastname", parachutist.getLastname()).append("id", countInt + 1) .append("birthdate", parachutist.getBirthdate()).append("gender", parachutist.getGender()) .append("street", parachutist.getStreet()).append("postnumber", parachutist.getPostnumber()) .append("postplace", parachutist.getPostplace()).append("mail", parachutist.getMail()) .append("phone", parachutist.getPhone()); dbCollectionParachutists.save(parachutistMongoObject); }
From source file:org.apache.isis.objectstore.nosql.db.mongo.MongoDb.java
License:Apache License
private void writeSerialNumber(final long serialNumber) { final DBCollection system = db.getCollection(SERIALNUMBERS_COLLECTION_NAME); DBObject object = system.findOne(); if (object == null) { object = new BasicDBObject(); }//from w ww .j a va 2 s . co m object.put("next-id", Long.toString(serialNumber)); system.save(object); LOG.info("serial number written: " + serialNumber); }
From source file:org.apache.isis.objectstore.nosql.db.mongo.MongoDb.java
License:Apache License
private long readSerialNumber() { final DBCollection system = db.getCollection(SERIALNUMBERS_COLLECTION_NAME); final DBObject data = system.findOne(); if (data == null) { return 0; } else {/* ww w . j a v a 2 s . c o m*/ final String number = (String) data.get("next-id"); LOG.info("serial number read: " + number); return Long.valueOf(number); } }
From source file:org.apache.rya.mongodb.instance.MongoRyaInstanceDetailsRepository.java
License:Apache License
@Override public RyaDetails getRyaInstanceDetails() throws NotInitializedException, RyaDetailsRepositoryException { // Preconditions. if (!isInitialized()) { throw new NotInitializedException("Could not fetch the details for the Rya instanced named '" + instanceName + "' because it has not been initialized yet."); }// w w w .ja v a2s . co m // Fetch the value from the collection. final DBCollection col = db.getCollection(INSTANCE_DETAILS_COLLECTION_NAME); //There should only be one document in the collection. final DBObject mongoObj = col.findOne(); try { // Deserialize it. return MongoDetailsAdapter.toRyaDetails(mongoObj); } catch (final MalformedRyaDetailsException e) { throw new RyaDetailsRepositoryException("The existing details details are malformed.", e); } }
From source file:org.einherjer.week2.samples.FindSample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findSample"); collection.drop();/* w ww.jav a 2s .c o m*/ // insert 10 documents with a random integer as the value of field "x" for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", new Random().nextInt(100))); } System.out.println("Find one:"); DBObject one = collection.findOne(); System.out.println(one); System.out.println("\nFind all: "); DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } System.out.println("\nCount:"); long count = collection.count(); System.out.println(count); }
From source file:org.exist.mongodb.xquery.mongodb.collection.FindOne.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {// w w w. j a va 2s . c o m // Verify clientid and get client String mongodbClientId = args[0].itemAt(0).getStringValue(); MongodbClientStore.getInstance().validate(mongodbClientId); MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId); // Get parameters String dbname = args[1].itemAt(0).getStringValue(); String collection = args[2].itemAt(0).getStringValue(); BasicDBObject query = (args.length >= 4) ? (BasicDBObject) JSON.parse(args[3].itemAt(0).getStringValue()) : null; BasicDBObject fields = (args.length >= 5) ? (BasicDBObject) JSON.parse(args[4].itemAt(0).getStringValue()) : null; BasicDBObject orderBy = (args.length >= 6) ? (BasicDBObject) JSON.parse(args[5].itemAt(0).getStringValue()) : null; // Check id MongodbClientStore.getInstance().validate(mongodbClientId); // Get database DB db = client.getDB(dbname); DBCollection dbcol = db.getCollection(collection); DBObject result; if (fields == null && orderBy == null && query == null) { result = dbcol.findOne(); } else if (fields == null && orderBy == null) { result = dbcol.findOne(query); } else if (orderBy == null) { result = dbcol.findOne(query, fields); } else { result = dbcol.findOne(query, fields, orderBy); } // Execute query Sequence retVal = (result == null) ? Sequence.EMPTY_SEQUENCE : new StringValue(result.toString()); return retVal; } catch (JSONParseException ex) { LOG.error(ex.getMessage()); throw new XPathException(this, MongodbModule.MONG0004, ex.getMessage()); } catch (XPathException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, ex.getMessage(), ex); } catch (MongoException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage()); } catch (Throwable ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0003, ex.getMessage()); } }
From source file:org.grails.datastore.mapping.mongo.query.MongoQuery.java
License:Apache License
@SuppressWarnings("hiding") @Override/*from w w w. j a va 2s.c o m*/ protected List executeQuery(final PersistentEntity entity, final Junction criteria) { final MongoTemplate template = mongoSession.getMongoTemplate(entity); return template.execute(new DbCallback<List>() { @SuppressWarnings("unchecked") public List doInDB(DB db) throws MongoException, DataAccessException { final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity)); if (uniqueResult) { final DBObject dbObject; if (criteria.isEmpty()) { if (entity.isRoot()) { dbObject = collection.findOne(); } else { dbObject = collection.findOne(new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD, entity.getDiscriminator())); } } else { dbObject = collection.findOne(getMongoQuery()); } return wrapObjectResultInList(createObjectFromDBObject(dbObject)); } DBCursor cursor = null; DBObject query = createQueryObject(entity); final List<Projection> projectionList = projections().getProjectionList(); if (projectionList.isEmpty()) { cursor = executeQuery(entity, criteria, collection, query); return (List) new MongoResultList(cursor, mongoEntityPersister).clone(); } List projectedResults = new ArrayList(); for (Projection projection : projectionList) { if (projection instanceof CountProjection) { // For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does //projectedResults.add(collection.getCount(query)); if (cursor == null) cursor = executeQuery(entity, criteria, collection, query); projectedResults.add(cursor.size()); } else if (projection instanceof MinProjection) { if (cursor == null) cursor = executeQuery(entity, criteria, collection, query); MinProjection mp = (MinProjection) projection; MongoResultList results = new MongoResultList(cursor, mongoEntityPersister); projectedResults.add(manualProjections.min((Collection) results.clone(), getPropertyName(entity, mp.getPropertyName()))); } else if (projection instanceof MaxProjection) { if (cursor == null) cursor = executeQuery(entity, criteria, collection, query); MaxProjection mp = (MaxProjection) projection; MongoResultList results = new MongoResultList(cursor, mongoEntityPersister); projectedResults.add(manualProjections.max((Collection) results.clone(), getPropertyName(entity, mp.getPropertyName()))); } else if (projection instanceof CountDistinctProjection) { if (cursor == null) cursor = executeQuery(entity, criteria, collection, query); CountDistinctProjection mp = (CountDistinctProjection) projection; MongoResultList results = new MongoResultList(cursor, mongoEntityPersister); projectedResults.add(manualProjections.countDistinct((Collection) results.clone(), getPropertyName(entity, mp.getPropertyName()))); } else if ((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) { final PersistentProperty persistentProperty; final String propertyName; if (projection instanceof IdProjection) { persistentProperty = entity.getIdentity(); propertyName = MongoEntityPersister.MONGO_ID_FIELD; } else { PropertyProjection pp = (PropertyProjection) projection; persistentProperty = entity.getPropertyByName(pp.getPropertyName()); propertyName = getPropertyName(entity, persistentProperty.getName()); } if (persistentProperty != null) { populateMongoQuery(entity, query, criteria); List propertyResults = null; if (max > -1) { // if there is a limit then we have to do a manual projection since the MongoDB driver doesn't support limits and distinct together cursor = executeQueryAndApplyPagination(collection, query); propertyResults = manualProjections .property(new MongoResultList(cursor, mongoEntityPersister), propertyName); } else { propertyResults = collection.distinct(propertyName, query); } if (persistentProperty instanceof ToOne) { Association a = (Association) persistentProperty; propertyResults = session.retrieveAll(a.getAssociatedEntity().getJavaClass(), propertyResults); } if (projectedResults.size() == 0 && projectionList.size() == 1) { return propertyResults; } projectedResults.add(propertyResults); } else { throw new InvalidDataAccessResourceUsageException( "Cannot use [" + projection.getClass().getSimpleName() + "] projection on non-existent property: " + propertyName); } } } return projectedResults; } protected DBCursor executeQuery(final PersistentEntity entity, final Junction criteria, final DBCollection collection, DBObject query) { final DBCursor cursor; if (criteria.isEmpty()) { cursor = executeQueryAndApplyPagination(collection, query); } else { populateMongoQuery(entity, query, criteria); cursor = executeQueryAndApplyPagination(collection, query); } if (queryArguments != null) { if (queryArguments.containsKey(HINT_ARGUMENT)) { Object hint = queryArguments.get(HINT_ARGUMENT); if (hint instanceof Map) { cursor.hint(new BasicDBObject((Map) hint)); } else if (hint != null) { cursor.hint(hint.toString()); } } } return cursor; } protected DBCursor executeQueryAndApplyPagination(final DBCollection collection, DBObject query) { final DBCursor cursor; cursor = collection.find(query); if (offset > 0) { cursor.skip(offset); } if (max > -1) { cursor.limit(max); } if (!orderBy.isEmpty()) { DBObject orderObject = new BasicDBObject(); for (Order order : orderBy) { String property = order.getProperty(); property = getPropertyName(entity, property); orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1); } cursor.sort(orderObject); } else { MongoCollection coll = (MongoCollection) entity.getMapping().getMappedForm(); if (coll != null && coll.getSort() != null) { DBObject orderObject = new BasicDBObject(); Order order = coll.getSort(); String property = order.getProperty(); property = getPropertyName(entity, property); orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1); cursor.sort(orderObject); } } return cursor; } }); }
From source file:org.pentaho.mongo.MongoUtils.java
License:Open Source License
/** * Return a list of custom "lastErrorModes" (if any) defined in the replica * set configuration object on the server. These can be used as the "w" * setting for the write concern in addition to the standard "w" values of * <number> or "majority".//from w w w .j ava 2 s . c o m * * @param hostsPorts the hosts to use * @param singlePort the default port to use if no ports are given in the * hostsPorts spec * @param username the username for authentication * @param password the password for authentication * @param vars the environment variables to use * @param log for logging * @return a list of the names of any custom "lastErrorModes" * @throws KettleException if a problem occurs */ public static List<String> getLastErrorModes(String hostsPorts, String singlePort, MongoCredential cred, VariableSpace vars, LogChannelInterface log) throws KettleException { List<String> customLastErrorModes = new ArrayList<String>(); MongoClient mongo = null; try { if (cred != null && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) { // need to make a new credential that specifies the local database cred = MongoCredential.createMongoCRCredential(cred.getUserName(), LOCAL_DB, cred.getPassword()); } mongo = initConnection(hostsPorts, singlePort, cred, false, null, null, null, null, null, false, null, vars, log); DB local = mongo.getDB(LOCAL_DB); if (local != null) { DBCollection replset = local.getCollection(REPL_SET_COLLECTION); if (replset != null) { DBObject config = replset.findOne(); extractLastErrorModes(config, customLastErrorModes); } } } finally { if (mongo != null) { mongo.close(); } } return customLastErrorModes; }
From source file:org.pentaho.mongo.MongoUtils.java
License:Open Source License
protected static BasicDBList getRepSetMemberRecords(String hostsPorts, String singlePort, MongoCredential cred, VariableSpace vars, LogChannelInterface log) throws KettleException { MongoClient mongo = null;/* ww w. jav a 2s .c om*/ BasicDBList setMembers = null; try { if (cred != null && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) { // need to make a new credential that specifies the local database cred = MongoCredential.createMongoCRCredential(cred.getUserName(), LOCAL_DB, cred.getPassword()); } mongo = initConnection(hostsPorts, singlePort, cred, false, null, null, null, null, null, false, null, vars, log); DB local = mongo.getDB(LOCAL_DB); if (local != null) { DBCollection replset = local.getCollection(REPL_SET_COLLECTION); if (replset != null) { DBObject config = replset.findOne(); if (config != null) { Object members = config.get(REPL_SET_MEMBERS); if (members instanceof BasicDBList) { if (((BasicDBList) members).size() == 0) { // log that there are no replica set members defined if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$ } } else { setMembers = (BasicDBList) members; } } else { // log that there are no replica set members defined if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$ } } } else { // log that there are no replica set members defined if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$ } } } else { // log that the replica set collection is not available if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.Warning.ReplicaSetCollectionUnavailable")); //$NON-NLS-1$ } } } else { // log that the local database is not available!! if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.Warning.LocalDBNotAvailable")); //$NON-NLS-1$ } } } catch (Exception ex) { throw new KettleException(ex); } finally { if (mongo != null) { mongo.close(); } } return setMembers; }