/** * 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 Document doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { Document id = collection.find(dbQuery).first(); return id; } });
@Nullable @Override public GridFSFile first() { return underlying.first(); }
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 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 GridFSFile getFileInfoById(@Nullable final ClientSession clientSession, final BsonValue id) { notNull("id", id); GridFSFile fileInfo = createFindIterable(clientSession, new Document("_id", id)).first(); if (fileInfo == null) { throw new MongoGridFSException(format("No file found with the id: %s", id)); } return fileInfo; }
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public Session get(final Builder builder) { return Optional.ofNullable(sessions.find(Filters.eq("_id", builder.sessionId())).first()) .map(doc -> { Map session = new LinkedHashMap<>(doc); Date accessedAt = (Date) session.remove("_accessedAt"); Date createdAt = (Date) session.remove("_createdAt"); Date savedAt = (Date) session.remove("_savedAt"); session.remove("_id"); builder .accessedAt(accessedAt.getTime()) .createdAt(createdAt.getTime()) .savedAt(savedAt.getTime()); session.forEach((k, v) -> builder.set(decode(k.toString()), v.toString())); return builder.build(); }).orElse(null); }
/** * 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(); } }
Document queryResult = findIterable.first();
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(); }
Document firstEvent = oplog.find().sort(new Document("$natural", 1)).limit(1).first(); // may be null return SourceInfo.extractEventTimestamp(firstEvent); });
@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")); }
@Test public void withDate() { final Date date = new Date(); final ObjectId id = ObjectId.get(); final Jackson expected = ImmutableJackson.builder() .id(id) .prop1("prop1") .prop2("22") .date(new Date(date.getTime())) .build(); repository.insert(expected).getUnchecked(); check(collection.count()).is(1L); final Jackson actual = repository.findAll().fetchAll().getUnchecked().get(0); check(expected).is(actual); final BsonDocument doc = collection.find().first(); check(doc.keySet()).hasContentInAnyOrder("_id", "prop1", "prop2", "date", "uuid"); check(doc.get("date").asDateTime().getValue()).is(date.getTime()); check(doc.get("_id").asObjectId().getValue()).is(id); }
doc = coll.find().first(); Testing.debug("Document: " + doc); id.set(doc.getObjectId("_id").toString()); Document doc = coll.find().first(); Testing.debug("Document: " + doc); Document filter = Document.parse("{\"a\": 1}"); coll.updateOne(filter, operation); doc = coll.find().first(); Testing.debug("Document: " + doc); });
public Document findMongoDocument(ServerConfiguration configuration, final MongoCollection mongoCollection, final Object _id) { TaskWithReturnedObject<Document> task = mongoClient -> { MongoDatabase mongoDatabase = mongoCollection.getParentDatabase(); com.mongodb.client.MongoDatabase database = mongoClient.getDatabase(mongoDatabase.getName()); com.mongodb.client.MongoCollection<Document> collection = database.getCollection(mongoCollection.getName()); FindIterable<Document> foundDocuments = collection.find(new BasicDBObject("_id", _id)); return foundDocuments.first(); }; return executeTask(configuration, task); }
/** * persist empty Optional of Date */ @Test public void nullDate() { final Jackson expected = ImmutableJackson.builder() .id(ObjectId.get()) .prop1("prop11") .prop2("prop22") .build(); repository.insert(expected).getUnchecked(); final Jackson actual = repository.findAll() .fetchAll().getUnchecked().get(0); check(expected.date().asSet()).isEmpty(); check(expected).is(actual); final BsonDocument doc = collection.find().first(); check(doc.keySet()).hasContentInAnyOrder("_id", "prop1", "prop2", "date", "uuid"); check(doc.get("date")).is(BsonNull.VALUE); }
@Override public Document fetch(DBRef dbRef) { StringUtils.hasText(dbRef.getDatabaseName()); return getCollection(dbRef).find(Filters.eq("_id", dbRef.getId())).first(); }
@Override public SessionData get(String sessionId) { Document doc = this.sessions .find(eq(SESSION_ID, sessionId)) .projection(include(SESSION_DATA)) .first(); if (doc == null) { return null; } String sessionStored = doc.getString(SESSION_DATA); SessionData sessionData = transcoder.decode(sessionStored); return sessionData; }