/** * Finds a single document in the collection according to the specified arguments. * * @param filter Bson filter */ public Document find(Bson filter) { //TODO batch finding return collection.find(filter).first(); }
public FindIterable<Document> doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { return collection.find(query, Document.class).projection(fields); } }
public Document doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { Document id = collection.find(dbQuery).first(); return id; } });
private Set<String> getTableMetadataNames(String schemaName) throws TableNotFoundException { MongoDatabase db = client.getDatabase(schemaName); MongoCursor<Document> cursor = db.getCollection(schemaCollection) .find().projection(new Document(TABLE_NAME_KEY, true)).iterator(); HashSet<String> names = new HashSet<>(); while (cursor.hasNext()) { names.add((cursor.next()).getString(TABLE_NAME_KEY)); } return names; }
private FindIterable<GridFSFile> createFindIterable(@Nullable final ClientSession clientSession, @Nullable final Bson filter) { FindIterable<GridFSFile> findIterable; if (clientSession != null) { findIterable = filesCollection.find(clientSession); } else { findIterable = filesCollection.find(); } if (filter != null) { findIterable = findIterable.filter(filter); } return findIterable; }
private MongoCursor<Document> getCursor(final int startChunkIndex) { FindIterable<Document> findIterable; Document filter = new Document("files_id", fileId).append("n", new Document("$gte", startChunkIndex)); if (clientSession != null) { findIterable = chunksCollection.find(clientSession, filter); } else { findIterable = chunksCollection.find(filter); } return findIterable.batchSize(batchSize).sort(new Document("n", 1)).iterator(); }
private <T> boolean collectionIsEmpty(@Nullable final ClientSession clientSession, final MongoCollection<T> collection) { if (clientSession != null) { return collection.find(clientSession).projection(new Document("_id", 1)).first() == null; } else { return collection.find().projection(new Document("_id", 1)).first() == null; } }
private Document findOne(Document query, Document projection) { MongoCollection col = controllerService.getDatabase(databaseName).getCollection(collection); MongoCursor<Document> it = (projection != null ? col.find(query).projection(projection) : col.find(query)).iterator(); Document retVal = it.hasNext() ? it.next() : null; it.close(); return retVal; } }
private List<Document> guessTableFields(SchemaTableName schemaTableName) { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); Document doc = db.getCollection(tableName).find().first(); if (doc == null) { // no records at the collection return ImmutableList.of(); } ImmutableList.Builder<Document> builder = ImmutableList.builder(); for (String key : doc.keySet()) { Object value = doc.get(key); Optional<TypeSignature> fieldType = guessFieldType(value); if (fieldType.isPresent()) { Document metadata = new Document(); metadata.append(FIELDS_NAME_KEY, key); metadata.append(FIELDS_TYPE_KEY, fieldType.get().toString()); metadata.append(FIELDS_HIDDEN_KEY, key.equals("_id") && fieldType.get().equals(OBJECT_ID.getTypeSignature())); builder.add(metadata); } else { log.debug("Unable to guess field type from %s : %s", value == null ? "null" : value.getClass().getName(), value); } } return builder.build(); }
private void removeConfigPath() { final FindIterable<Document> documentsWithConfigPath = collection.find(exists("configuration_path")); for (Document document : documentsWithConfigPath) { final ObjectId objectId = document.getObjectId("_id"); document.remove("configuration_path"); final UpdateResult updateResult = collection.replaceOne(eq("_id", objectId), document); if (updateResult.wasAcknowledged()) { LOG.debug("Successfully updated document with ID <{}>", objectId); } else { LOG.error("Failed to update document with ID <{}>", objectId); } } }
/** * Obtain the current position of the oplog, and record it in the source. */ protected void recordCurrentOplogPosition() { primaryClient.execute("get oplog position", primary -> { MongoCollection<Document> oplog = primary.getDatabase("local").getCollection("oplog.rs"); Document last = oplog.find().sort(new Document("$natural", -1)).limit(1).first(); // may be null source.offsetStructForEvent(replicaSet.replicaSetName(), last); }); }
public Document doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { FindIterable<Document> iterable = collection.find(query, Document.class); if (LOGGER.isDebugEnabled()) { LOGGER.debug("findOne using query: {} fields: {} in db.collection: {}", serializeToJsonSafely(query), serializeToJsonSafely(fields.orElseGet(Document::new)), collection.getNamespace() != null ? collection.getNamespace().getFullName() : "n/a"); } if (fields.isPresent()) { iterable = iterable.projection(fields.get()); } return iterable.first(); } }
@Signature public WrapMongoIterable find(Environment env) { return new WrapMongoIterable(env, getWrappedObject().find(Document.class)); }
@Signature public WrapMongoIterable find(Environment env, BasicDBObject filter) { return new WrapMongoIterable(env, getWrappedObject().find(filter, Document.class)); }
private Document getTableMetadata(SchemaTableName schemaTableName) throws TableNotFoundException { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); MongoCollection<Document> schema = db.getCollection(schemaCollection); Document doc = schema .find(new Document(TABLE_NAME_KEY, tableName)).first(); if (doc == null) { if (!collectionExists(db, tableName)) { throw new TableNotFoundException(schemaTableName); } else { Document metadata = new Document(TABLE_NAME_KEY, tableName); metadata.append(FIELDS_KEY, guessTableFields(schemaTableName)); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); return metadata; } } return doc; }
@Override public Document fetch(DBRef dbRef) { StringUtils.hasText(dbRef.getDatabaseName()); return getCollection(dbRef).find(Filters.eq("_id", dbRef.getId())).first(); }
public MongoCursor<Document> execute(MongoSplit split, List<MongoColumnHandle> columns) { Document output = new Document(); for (MongoColumnHandle column : columns) { output.append(column.getName(), 1); } MongoCollection<Document> collection = getCollection(split.getSchemaTableName()); FindIterable<Document> iterable = collection.find(buildQuery(split.getTupleDomain())).projection(output); if (cursorBatchSize != 0) { iterable.batchSize(cursorBatchSize); } return iterable.iterator(); }
@Override public void upgrade() { final FindIterable<Document> documentsWithMissingFields = collection.find(or(not(exists(ContentPack.FIELD_META_ID)), not(exists(ContentPack.FIELD_META_REVISION)))); for (Document document : documentsWithMissingFields) { final ObjectId objectId = document.getObjectId("_id"); LOG.debug("Found document with missing \"id\" or \"rev\" field with ID <{}>", objectId); final String id = document.get("id", objectId.toHexString()); final int rev = document.get("rev", 0); document.put("id", id); document.put("rev", rev); final UpdateResult updateResult = collection.replaceOne(eq("_id", objectId), document); if (updateResult.wasAcknowledged()) { LOG.debug("Successfully updated document with ID <{}>", objectId); } else { LOG.error("Failed to update document with ID <{}>", objectId); } } } }
@Test public void simpleMongoDbTest() { MongoClient mongoClient = new MongoClient(mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_PORT)); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("testCollection"); Document doc = new Document("name", "foo") .append("value", 1); collection.insertOne(doc); Document doc2 = collection.find(new Document("name", "foo")).first(); assertEquals("A record can be inserted into and retrieved from MongoDB", 1, doc2.get("value")); }
@Override public CloseableIterator<T> doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { MongoPersistentEntity<?> persistentEntity = mappingContext.getRequiredPersistentEntity(entityType); Document mappedFields = getMappedFieldsObject(query.getFieldsObject(), persistentEntity, returnType); Document mappedQuery = queryMapper.getMappedObject(query.getQueryObject(), persistentEntity); FindIterable<Document> cursor = new QueryCursorPreparer(query, entityType) .prepare(collection.find(mappedQuery, Document.class).projection(mappedFields)); return new CloseableIterableCursorAdapter<>(cursor, exceptionTranslator, new ProjectingReadCallback<>(mongoConverter, entityType, returnType, collectionName)); } });