@SuppressWarnings("unchecked") @Override public <S> S read(Class<S> clazz, Bson source) { Document document = (Document) source; return (S) ((document.get("fname") + ", ") + document.get("lname") + ", " + document.get("city") + ", " + document.get("street") + ", " + document.get("zip") + ", " + document.get("state") + ", "); }
public static List<MongoIndex> parse(ListIndexesIterable<Document> indexes) { ImmutableList.Builder<MongoIndex> builder = ImmutableList.builder(); for (Document index : indexes) { // TODO: v, ns, sparse fields Document key = (Document) index.get("key"); String name = index.getString("name"); boolean unique = index.getBoolean("unique", false); if (key.containsKey("_fts")) { // Full Text Search continue; } builder.add(new MongoIndex(name, parseKey(key), unique)); } return builder.build(); }
@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); } } } }
/** * Utility to extract the {@link BsonTimestamp timestamp} value from the event. * * @param oplogEvent the event * @return the timestamp, or null if the event is null or there is no {@code ts} field */ protected static BsonTimestamp extractEventTimestamp(Document oplogEvent) { return oplogEvent != null ? oplogEvent.get("ts", BsonTimestamp.class) : null; }
private List<Document> getColumnMetadata(Document doc) { if (!doc.containsKey(FIELDS_KEY)) { return ImmutableList.of(); } return (List<Document>) doc.get(FIELDS_KEY); }
@Override public GeoJsonMultiPoint convert(Document source) { if (source == null) { return null; } Assert.isTrue(ObjectUtils.nullSafeEquals(source.get("type"), "MultiPoint"), String.format("Cannot convert type '%s' to MultiPoint.", source.get("type"))); List cords = (List) source.get("coordinates"); return new GeoJsonMultiPoint(toListOfPoint(cords)); } }
private static List<MongodbIndexKey> parseKey(Document key) { ImmutableList.Builder<MongodbIndexKey> builder = ImmutableList.builder(); for (String name : key.keySet()) { Object value = key.get(name); if (value instanceof Number) { int order = ((Number) value).intValue(); checkState(order == 1 || order == -1, "Unknown index sort order"); builder.add(new MongodbIndexKey(name, order == 1 ? SortOrder.ASC_NULLS_LAST : SortOrder.DESC_NULLS_LAST)); } else if (value instanceof String) { builder.add(new MongodbIndexKey(name, (String) value)); } else { throw new UnsupportedOperationException("Unknown index type: " + value.toString()); } } return builder.build(); }
@Override public ConvertToIndex equal(String name, boolean negate, @Nullable Object value) { if (document.containsKey(name)) { throw new IllegalArgumentException( String.format("Attribute %s is not unique: %s", name, document.get(name))); } document.put(name, value); return this; } }
@Override public Point convert(Document source) { if (source == null) { return null; } Assert.isTrue(source.keySet().size() == 2, "Source must contain 2 elements"); if (source.containsKey("type")) { return DocumentToGeoJsonPointConverter.INSTANCE.convert(source); } return new Point(toPrimitiveDoubleValue(source.get("x")), toPrimitiveDoubleValue(source.get("y"))); } }
@Override public List<T> multiGet(List<List<Object>> keysList) { List<T> retval = new ArrayList<>(); try { for (List<Object> keys : keysList) { Bson filter = options.queryCreator.createFilterByKeys(keys); Document doc = mongoClient.find(filter); if (doc != null) { retval.add(this.serializer.deserialize((byte[])doc.get(options.serDocumentField))); } else { retval.add(null); } } } catch (Exception e) { LOG.warn("Batch get operation failed.", e); throw new FailedException(e); } return retval; }
protected String idObjToJson(Object idObj) { if (idObj == null) { return null; } if (!(idObj instanceof Document)) { return jsonSerializer.serialize(idObj); } return jsonSerializer.serialize( ((Document)idObj).get(DBCollection.ID_FIELD_NAME) ); }
private Object resolve(Object value, AggregationOperationContext context) { if (value instanceof Field) { return context.getReference((Field) value).toString(); } else if (value instanceof AggregationExpression) { return ((AggregationExpression) value).toDocument(context); } else if (value instanceof Document) { return value; } return context.getMappedObject(new Document("$set", value)).get("$set"); }
private Object resolveValue(AggregationOperationContext context, Object value) { if (value instanceof Document || value instanceof Field) { return resolve(context, value); } if (value instanceof AggregationExpression) { return ((AggregationExpression) value).toDocument(context); } return context.getMappedObject(new Document("$set", value)).get("$set"); }
@Override public List<Values> toTuple(ITuple input, Document doc) { Values values = new Values(); for (String field : fields) { if (input.contains(field)) { values.add(input.getValueByField(field)); } else { values.add(doc.get(field)); } } List<Values> result = new ArrayList<Values>(); result.add(values); return result; }
@SuppressWarnings("unchecked") private Document getValidation() { Document document = getMongoClient().getDatabase(TEST_DB_NAME) .runCommand(new Document("listCollections", 1) .append("filter", new Document("name", "validation"))); List<Document> firstBatch = (List<Document>) ((Document) document.get("cursor")).get("firstBatch"); return (Document) firstBatch.get(0).get("options"); }
@Override public Object doInDB(MongoDatabase db) throws MongoException, DataAccessException { Document command = new Document("$eval", script.getCode()); BasicDBList commandArgs = new BasicDBList(); commandArgs.addAll(Arrays.asList(convertScriptArgs(false, args))); command.append("args", commandArgs); return db.runCommand(command).get("retval"); } });
@Override public Page getNextPage() { verify(pageBuilder.isEmpty()); count = 0; for (int i = 0; i < ROWS_PER_REQUEST; i++) { if (!cursor.hasNext()) { finished = true; break; } currentDoc = cursor.next(); count++; pageBuilder.declarePosition(); for (int column = 0; column < columnTypes.size(); column++) { BlockBuilder output = pageBuilder.getBlockBuilder(column); appendTo(columnTypes.get(column), currentDoc.get(columnNames.get(column)), output); } } Page page = pageBuilder.build(); pageBuilder.reset(); return page; }
@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")); }
private void checkValidation(final Document validator, final MappedClass mappedClass, final ValidationLevel level, final ValidationAction action) { updateValidation(mappedClass, level, action); Document expected = new Document("validator", validator) .append("validationLevel", level.getValue()) .append("validationAction", action.getValue()); Document validation = getValidation(); for (String key : expected.keySet()) { assertEquals(expected.get(key), validation.get(key)); } }