/** * Returns {@literal true} if the given {@link Document} is an update object that uses update operators. * * @param updateObj can be {@literal null}. * @return {@literal true} if the given {@link Document} is an update object. */ public static boolean isUpdateObject(@Nullable Document updateObj) { if (updateObj == null) { return false; } for (String s : updateObj.keySet()) { if (s.startsWith("$")) { return true; } } return false; }
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(); }
private List<Object> extractArgumentListFrom(Document context) { return (List<Object>) context.get(context.keySet().iterator().next()); } }
private Document mergeConjunctions(List<Document> conjunctions) { final Multimap<String, Document> merged = LinkedHashMultimap.create(); for (Document doc : conjunctions) { Preconditions.checkState(doc.keySet().size() == 1, "Invalid constraint %s", doc); final String key = doc.keySet().iterator().next(); merged.put(key, doc); } final Document result = new Document(); for (Map.Entry<String, Collection<Document>> entry : merged.asMap().entrySet()) { Preconditions.checkState(!entry.getValue().isEmpty(), "empty constraint: %s", entry); if (entry.getValue().size() == 1) { result.putAll(entry.getValue().iterator().next()); } else { result.putAll(new Document(QueryOperators.AND, entry.getValue())); } } return result; }
private List<Object> getClauses(AggregationOperationContext context, Document mappedObject) { List<Object> clauses = new ArrayList<Object>(); for (String key : mappedObject.keySet()) { Object predicate = mappedObject.get(key); clauses.addAll(getClauses(context, key, predicate)); } return clauses; }
protected Object insertDocument(final String collectionName, final Document document, final Class<?> entityClass) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Inserting Document containing fields: {} in collection: {}", document.keySet(), collectionName); } return execute(collectionName, new CollectionCallback<Object>() { public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName, entityClass, document, null); WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction); if (writeConcernToUse == null) { collection.insertOne(document); } else { collection.withWriteConcern(writeConcernToUse).insertOne(document); } return operations.forEntity(document).getId(); } }); }
private org.bson.Document resolveCompoundIndexKeyFromStringDefinition(String dotPath, String keyDefinitionString) { if (!StringUtils.hasText(dotPath) && !StringUtils.hasText(keyDefinitionString)) { throw new InvalidDataAccessApiUsageException("Cannot create index on root level for empty keys."); } if (!StringUtils.hasText(keyDefinitionString)) { return new org.bson.Document(dotPath, 1); } org.bson.Document dbo = org.bson.Document.parse(keyDefinitionString); if (!StringUtils.hasText(dotPath)) { return dbo; } org.bson.Document document = new org.bson.Document(); for (String key : dbo.keySet()) { document.put(dotPath + "." + key, dbo.get(key)); } return document; }
private List<Object> getClauses(AggregationOperationContext context, String key, Object predicate) { List<Object> clauses = new ArrayList<Object>(); if (predicate instanceof List) { List<Object> args = new ArrayList<Object>(); for (Object clause : (List<?>) predicate) { if (clause instanceof Document) { args.addAll(getClauses(context, (Document) clause)); } } clauses.add(new Document(key, args)); } else if (predicate instanceof Document) { Document nested = (Document) predicate; for (String s : nested.keySet()) { if (!isKeyword(s)) { continue; } List<Object> args = new ArrayList<Object>(); args.add("$" + key); args.add(nested.get(s)); clauses.add(new Document(s, args)); } } else if (!isKeyword(key)) { List<Object> args = new ArrayList<Object>(); args.add("$" + key); args.add(predicate); clauses.add(new Document("$eq", args)); } return clauses; }
protected Object saveDocument(final String collectionName, final Document dbDoc, final Class<?> entityClass) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Saving Document containing fields: {}", dbDoc.keySet()); } return execute(collectionName, new CollectionCallback<Object>() { public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException { MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName, entityClass, dbDoc, null); WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction); MappedDocument mapped = MappedDocument.of(dbDoc); if (!mapped.hasId()) { if (writeConcernToUse == null) { collection.insertOne(dbDoc); } else { collection.withWriteConcern(writeConcernToUse).insertOne(dbDoc); } } else if (writeConcernToUse == null) { collection.replaceOne(mapped.getIdFilter(), dbDoc, new ReplaceOptions().upsert(true)); } else { collection.withWriteConcern(writeConcernToUse).replaceOne(mapped.getIdFilter(), dbDoc, new ReplaceOptions().upsert(true)); } return mapped.getId(); } }); }
public Document getCriteriaObject() { if (this.criteriaChain.size() == 1) { return criteriaChain.get(0).getSingleCriteriaObject(); } else if (CollectionUtils.isEmpty(this.criteriaChain) && !CollectionUtils.isEmpty(this.criteria)) { return getSingleCriteriaObject(); } else { Document criteriaObject = new Document(); for (Criteria c : this.criteriaChain) { Document document = c.getSingleCriteriaObject(); for (String k : document.keySet()) { setValue(criteriaObject, k, document.get(k)); } } return criteriaObject; } }
private Document mapProperties(@Nullable PersistentEntity<?, MongoPersistentProperty> entity, Document source) { Document sink = new Document(); for (String fieldName : source.keySet()) { String mappedFieldName = getFieldName(entity, fieldName); Document mappedProperty = mapProperty(entity, fieldName, source.get(fieldName, Document.class)); sink.append(mappedFieldName, mappedProperty); } return sink; }
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(); }
List<TypeSignatureParameter> parameters = new ArrayList<>(); for (String key : ((Document) value).keySet()) { Optional<TypeSignature> fieldType = guessFieldType(((Document) value).get(key)); if (!fieldType.isPresent()) {
@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"))); } }
protected Mono<Object> insertDocument(String collectionName, Document dbDoc, Class<?> entityClass) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Inserting Document containing fields: " + dbDoc.keySet() + " in collection: " + collectionName); } Document document = new Document(dbDoc); Flux<Success> execute = execute(collectionName, collection -> { MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName, entityClass, dbDoc, null); WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction); MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse); return collectionToUse.insertOne(document); }); return Flux.from(execute).last().map(success -> MappedDocument.of(document).getId()); }
@Override public T doWith(@Nullable Document object) { if (object == null) { return null; } Object idField = object.get(Fields.UNDERSCORE_ID); if (!(idField instanceof Document)) { return super.doWith(object); } Document toMap = new Document(); Document nested = (Document) idField; toMap.putAll(nested); for (String key : object.keySet()) { if (!Fields.UNDERSCORE_ID.equals(key)) { toMap.put(key, object.get(key)); } } return super.doWith(toMap); } }
protected Mono<Object> saveDocument(String collectionName, Document document, Class<?> entityClass) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Saving Document containing fields: " + document.keySet()); } return createMono(collectionName, collection -> { MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName, entityClass, document, null); WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction); MappedDocument mapped = MappedDocument.of(document); MongoCollection<Document> collectionToUse = writeConcernToUse == null // ? collection // : collection.withWriteConcern(writeConcernToUse); Publisher<?> publisher = !mapped.hasId() // ? collectionToUse.insertOne(document) // : collectionToUse.replaceOne(mapped.getIdFilter(), document, new ReplaceOptions().upsert(true)); return Mono.from(publisher).map(o -> mapped.getId()); }); }
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)); } }
@Test public void embeddedIndexPartialFilters() { getMorphia().map(FeedEvent.class, InboxEvent.class); getDs().ensureIndexes(); final MongoCollection<Document> inboxEvent = getDatabase().getCollection("InboxEvent"); for (final Document index : inboxEvent.listIndexes()) { if (!"_id_".equals(index.get("name"))) { for (String name : index.get("key", Document.class).keySet()) { Assert.assertTrue("Key names should start with the field name: " + name, name.startsWith("feedEvent.")); } } } // check the logging is disabled inboxEvent.drop(); final Builder builder = MapperOptions .builder(getMorphia().getMapper().getOptions()) .disableEmbeddedIndexes(true); getMorphia().getMapper().setOptions(builder.build()); getDs().ensureIndexes(); Assert.assertNull("No indexes should be generated for InboxEvent", inboxEvent.listIndexes().iterator().tryNext()); }