### Wrapper Style GridFS Mapping Example Source: https://github.com/morphiaorg/morphia/blob/master/design/GridFS.adoc An example entity class demonstrating the use of the GridFSItem wrapper for mapping GridFS data. This approach offers lazy loading by default and explicit methods for stream access and deletion. ```java @Entity public class ImageUpload { @Id private ObjectId id; ``` -------------------------------- ### Basic Aggregation Pipeline Start Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregations.adoc Initiates an aggregation pipeline against a specific Morphia entity class. Ensure document fields referenced in the pipeline exist. ```java var aggregation = datastore.aggregate(Book.class); aggregation.group(fields().and("author"), fields().and("books", Aggregation.addToSet("title"))); ``` -------------------------------- ### Update Datastore Operation (After) Source: https://github.com/morphiaorg/morphia/blob/master/Migration.md Example of an update operation using the new fluent API with Query as the entry point. ```java getDs().find(SomeEntity.class) .field("name").equalIgnoreCase("Robert") .update() .removeAll("nicknames", "Shorty") .execute(); ``` -------------------------------- ### Traditional GridFS Mapping Example Source: https://github.com/morphiaorg/morphia/blob/master/design/GridFS.adoc Illustrates mapping an Image object to GridFS using the @GridFS annotation. This approach requires proxying for lazy loading and may necessitate a custom Codec. ```java @Entity public class ImageUpload { @Id private ObjectId id; private double[] coordinates; private String[] tags; @GridFS("images") private Image image; } ``` -------------------------------- ### Update Datastore Operation (Before) Source: https://github.com/morphiaorg/morphia/blob/master/Migration.md Example of an update operation using the older Datastore API. ```java getDs().update( getDs().find(SomeEntity.class).field("name").equalIgnoreCase("Robert"), getAds().createUpdateOperations(SomeEntity.class) .removeAll("nicknames", "Shorty")); ``` -------------------------------- ### Create Morphia Datastore Instance Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/quicktour.adoc Creates the initial Morphia instance for configuring entity mapping and query validation. This minimal setup uses a default database and scans the classpath for entities. ```java final Datastore datastore = Morphia.createDatastore(MongoClients.create()); ``` -------------------------------- ### Manually Manage Transaction Boundaries Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/transactions.adoc For more control, manually start a session, begin a transaction, perform operations using the session, and then commit the transaction. Ensure the session is closed afterwards. ```java MorphiaSession session = datastore.startSession(); session.startTransaction(); User user = new User("jimbo", "jimhalpert@dundermifflin.com"); user.setHomeAddress(new Address("123 Paper Lane", "Scranton", "PA", "18510")); session.save(user); session.commitTransaction(); session.close(); ``` -------------------------------- ### StringExpressions.indexOfCP Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Returns the starting code point index of the first occurrence of a substring within a string. ```APIDOC ## indexOfCP(Object, Object) ### Description Finds the first occurrence of a substring within a string based on code points and returns its index. ### Method `indexOfCP(Object string, Object substring)` ### Parameters - **string** (Object) - The string to search within. - **substring** (Object) - The substring to search for. ### Request Example ```java StringExpressions.indexOfCP(fieldString, "hello") ``` ### Response Returns the 0-based code point index of the first occurrence of the substring, or -1 if not found. ``` -------------------------------- ### Prepare Filtered Query for Update Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/quicktour.adoc Constructs a query to select entities based on a filter, preparing them for subsequent update operations. This example selects employees with a salary less than or equal to 30000. ```java final Query underPaidQuery = datastore.find(Employee.class) .filter(Filters.lte("salary", 30000)); ``` -------------------------------- ### StringExpressions.indexOfBytes Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Returns the starting byte index of the first occurrence of a substring within a string. ```APIDOC ## indexOfBytes(Object, Object) ### Description Locates the first occurrence of a substring within a string and returns its starting byte index. ### Method `indexOfBytes(Object string, Object substring)` ### Parameters - **string** (Object) - The string to search within. - **substring** (Object) - The substring to search for. ### Request Example ```java StringExpressions.indexOfBytes(fieldString, "world") ``` ### Response Returns the 0-based byte index of the first occurrence of the substring, or -1 if not found. ``` -------------------------------- ### Perform multiple updates Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/updates.adoc Modify multiple documents matching the query by setting the `multi(true)` option in `UpdateOptions`. This example increments the 'stars' field. ```java datastore .find(Hotel.class) .update(new UpdateOptions() .multi(true), UpdateOperators.inc("stars")); ``` -------------------------------- ### Perform an upsert operation Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/updates.adoc Use `UpdateOptions.upsert(true)` to create a new document if no documents match the query criteria. This example finds hotels with more than 100 stars and creates one if none exist. ```java datastore .find(Hotel.class, new UpdateOptions() .upsert(true)) .filter(gt("stars", 100)) .update(); // creates { "_id" : ObjectId("4c60629d2f1200000000161d"), "stars" : 50 } ``` -------------------------------- ### Sort Documents by Multiple Fields Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/queries.adoc Use `ascending` and `descending` with `FindOptions.sort()` to define multi-field sorting criteria. This example sorts by age (youngest first) and then income (highest first). ```java getDs().find(User.class) .iterator(new FindOptions() .sort(ascending("age"), descending("income")) .limit(1)) .tryNext(); ``` -------------------------------- ### Return updated entity after modification Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/updates.adoc Use `Query#modify()` with `ModifyOptions` to return the document either before or after the update. This example returns the entity in its state after the city field is updated. ```java datastore .find(Hotel.class, new ModifyOptions() .returnDocument(ReturnDocument.AFTER)) .modify(UpdateOperators.set("address.city", "Ottawa")); ``` -------------------------------- ### Add critter-maven Plugin to pom.xml Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/maven-plugin.adoc Configure your pom.xml to include the critter-maven plugin. This setup ensures the plugin is bound to the correct execution phase for generating Morphia models. ```xml dev.morphia.morphia critter-maven ${morphia.version} generate-critter generate-models ``` -------------------------------- ### Build and Publish Release with Gradle Source: https://github.com/morphiaorg/morphia/blob/master/rewrite/README.md Run this command to build a release version of your recipe, tag it, and publish it to the artifact repository. ```bash ./gradlew final publish ``` -------------------------------- ### Build and Publish Snapshot with Gradle Source: https://github.com/morphiaorg/morphia/blob/master/rewrite/README.md Run this command to build a snapshot version of your recipe and publish it to the artifact repository. ```bash ./gradlew snapshot publish ``` -------------------------------- ### Publish to Maven Local with Gradle Source: https://github.com/morphiaorg/morphia/blob/master/rewrite/README.md Use this command to publish your recipe module to your local Maven repository for testing. ```bash ./gradlew publishToMavenLocal # or ./gradlew pTML ``` -------------------------------- ### Define Hotel Entity Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/updates.adoc Example of a Morphia entity class for a Hotel, including embedded Address. ```java @Entity("hotels") public class Hotel { @Id private ObjectId id; private String name; private int stars; @Embedded private Address address; List roomNumbers = new ArrayList(); // ... getters and setters } @Embedded public class Address { private String street; private String city; private String postalCode; private String country; // ... getters and setters } ``` -------------------------------- ### Load Morphia Configuration from File Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/migrating.adoc Load Morphia configuration from a `META-INF/morphia-config.properties` file. This provides a `MorphiaConfig` instance configured according to the file's contents, useful for Morphia 2.4's file-based configuration. ```java MorphiaConfig#load() ``` -------------------------------- ### Run Kotlin Upgrade Script Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/migrating.adoc Use this command to execute the Kotlin upgrade script for migrating from Morphia 2.2 to 2.3. You may be prompted to set a trust level for the script. ```shell jbang https://github.com/MorphiaOrg/morphia/blob/master/upgrading/UpgradeFrom22to23.kt ``` -------------------------------- ### Clone Morphia Repository and Create Branch Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/issues-help.adoc Use these bash commands to clone the Morphia repository and set up a new branch for your feature development. ```bash $ git clone https://github.com/MorphiaOrg/morphia.git $ cd morphia $ git checkout -b myNewFeature ``` -------------------------------- ### Configure Legacy Mapper Options Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/migrating.adoc Replace `MappingOptions.legacy().build()` with this explicit configuration to preserve older mapping styles while enabling the modern query API. This is necessary as the `legacy()` option is removed in Morphia 3.0. ```java MapperOptions.builder() .discriminatorKey("className") .discriminator(DiscriminatorFunction.className()) .collectionNaming(NamingStrategy.identity()) .propertyNaming(NamingStrategy.identity()) ``` -------------------------------- ### Runtime Model Loading with CritterMapper Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/maven-plugin.adoc Shows how CritterMapper attempts to load pre-generated entity models at runtime. If found, it bypasses runtime generation and reflection, leading to faster entity mapping. ```text Runtime (morphia.mapper=critter) └─ CritterMapper.mapEntity(Hotel.class) 1. tryLoadPregenerated() → finds HotelEntityModel on classpath ✓ 2. (skipped) → no runtime generation needed 3. (skipped) → no reflection fallback needed ``` -------------------------------- ### Configure Morphia Critter Mapper Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/configuration.adoc Set this property in `META-INF/morphia-config.properties` to enable the `critter` bytecode-generation mapper for improved performance. ```txt morphia.mapper=critter ``` -------------------------------- ### Manage Session with try-with-resources Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/transactions.adoc Utilize a try-with-resources block to automatically manage the lifecycle of a MorphiaSession, ensuring it is closed even if exceptions occur during transaction processing. ```java try(MorphiaSession session = datastore.startSession()) { session.startTransaction(); User user = new User("jimbo", "jimhalpert@dundermifflin.com"); user.setHomeAddress(new Address("123 Paper Lane", "Scranton", "PA", "18510")); session.save(user); session.commitTransaction(); } ``` -------------------------------- ### BucketAuto Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $bucketAuto stage groups input documents into a specified number of buckets, automatically determining the bucket boundaries. ```APIDOC ## BucketAuto Stage ### Description Groups input documents into a specified number of buckets, automatically determining the bucket boundaries. ### Method `AutoBucket.autoBucket()` ### Endpoint N/A (This is a Java API stage) ### Parameters None directly on the `autoBucket()` method, parameters are configured within the `AutoBucket` builder. ### Request Example ```java // Example usage within a Morphia aggregation pipeline aggregationPipeline.addStage(AutoBucket.autoBucket().groupBy("$score").buckets(5).output("count", new Document("$sum", 1))); ``` ### Response N/A (This stage groups documents within the pipeline) ``` -------------------------------- ### Run OpenRewrite for Morphia 2.2 to 2.3 Migration Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/migrating.adoc Execute an OpenRewrite recipe to automate the migration from Morphia 2.2 to 2.3. This script handles package name changes (removing `.experimental`) and can update the Morphia version in your pom.xml. ```shell mvn org.openrewrite.maven:rewrite-maven-plugin:4.37.0:runNoFork -DactiveRecipes=dev.morphia.UpgradeFrom22to23 ``` -------------------------------- ### Entity with @PrePersist Callbacks Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/life-cycle-methods.adoc Define @PrePersist methods directly on the entity to execute logic before saving. These methods can optionally accept a Document for manipulation or return a Document. ```java class BankAccount { @Id String id; Date lastUpdated = new Date(); @PrePersist public void trackUpdate() { lastUpdated = new Date(); } @PrePersist public void prePersist( Document document) { // perform operations on serialized form of the entity } } ``` -------------------------------- ### Generate Morphia Configuration from MapperOptions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/migrating.adoc Manually generate the content for `META-INF/morphia-config.properties` by converting an existing `MapperOptions` instance. This is useful for migrating to Morphia 2.4's file-based configuration. ```java MapperOptions#toConfigFormat(String database, boolean showComplete) ``` -------------------------------- ### Window Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Documentation for window aggregation expressions like shift, stdDevPop, and stdDevSamp. ```APIDOC ## shift ### Description Accesses a document in a specified position within a window frame. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## stdDevPop ### Description Calculates the population standard deviation of the values in a group. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## stdDevSamp ### Description Calculates the sample standard deviation of the values in a group. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Morphia Aggregation Pipeline Stages Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/morphia-2.5-3.0-table.adoc Methods for building and executing aggregation pipelines in Morphia. ```APIDOC ## Aggregation ### Description Provides methods to construct and execute aggregation pipelines. ### Methods `abstract dev.morphia.aggregation.Aggregation addFields(dev.morphia.aggregation.stages.AddFields)` `abstract dev.morphia.aggregation.Aggregation addStage(dev.morphia.aggregation.stages.Stage)` `abstract dev.morphia.aggregation.Aggregation autoBucket(dev.morphia.aggregation.stages.AutoBucket)` `abstract dev.morphia.aggregation.Aggregation bucket(dev.morphia.aggregation.stages.Bucket)` `abstract dev.morphia.aggregation.Aggregation changeStream()` `abstract dev.morphia.aggregation.Aggregation changeStream(dev.morphia.aggregation.stages.ChangeStream)` `abstract dev.morphia.aggregation.Aggregation collStats(dev.morphia.aggregation.stages.CollectionStats)` `abstract dev.morphia.aggregation.Aggregation count(java.lang.String)` `abstract dev.morphia.aggregation.Aggregation currentOp(dev.morphia.aggregation.stages.CurrentOp)` `abstract dev.morphia.aggregation.Aggregation densify(dev.morphia.aggregation.stages.Densify)` `abstract dev.morphia.aggregation.Aggregation documents(dev.morphia.aggregation.expressions.impls.DocumentExpression)` `abstract dev.morphia.query.internal.MorphiaCursor execute(java.lang.Class)` `abstract dev.morphia.query.internal.MorphiaCursor execute(java.lang.Class, dev.morphia.aggregation.AggregationOptions)` `abstract dev.morphia.aggregation.Aggregation facet(dev.morphia.aggregation.stages.Facet)` `abstract dev.morphia.aggregation.Aggregation fill(dev.morphia.aggregation.stages.Fill)` `abstract dev.morphia.aggregation.Aggregation geoNear(dev.morphia.aggregation.stages.GeoNear)` `abstract dev.morphia.aggregation.Aggregation graphLookup(dev.morphia.aggregation.stages.GraphLookup)` `abstract dev.morphia.aggregation.Aggregation group(dev.morphia.aggregation.stages.Group)` `abstract dev.morphia.aggregation.Aggregation indexStats()` `abstract dev.morphia.query.MorphiaCursor iterator()` `abstract dev.morphia.aggregation.Aggregation limit(long)` `abstract dev.morphia.aggregation.Aggregation lookup(dev.morphia.aggregation.stages.Lookup)` `abstract dev.morphia.aggregation.Aggregation match(dev.morphia.query.filters.Filter)` `abstract dev.morphia.aggregation.void merge(dev.morphia.aggregation.stages.Merge)` `abstract dev.morphia.aggregation.void merge(dev.morphia.aggregation.stages.Merge, dev.morphia.aggregation.AggregationOptions)` `abstract dev.morphia.aggregation.void out(dev.morphia.aggregation.stages.Out)` `abstract dev.morphia.aggregation.void out(dev.morphia.aggregation.stages.Out, dev.morphia.aggregation.AggregationOptions)` ``` -------------------------------- ### Configure Gradle for Custom Recipes Source: https://github.com/morphiaorg/morphia/blob/master/rewrite/README.md Configure your root Gradle build to resolve custom recipe modules by adding them to the 'rewrite' configuration and specifying repositories. ```groovy plugins { id("java") id("org.openrewrite.rewrite") version "latest.release" } repositories { mavenLocal() mavenCentral() } dependencies { rewrite("com.yourorg:rewrite-recipe-starter:latest.integration") } rewrite { activeRecipe("com.yourorg.NoGuavaListsNewArrayList") } ``` -------------------------------- ### Create a New Query Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/queries.adoc Instantiate a Query object for a specific entity class. ```java Query query = datastore.find(Product.class); ``` -------------------------------- ### Run Morphia Build Checks Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/issues-help.adoc Execute Maven to perform code audits and ensure the build passes after making changes. ```bash $ cd core $ mvn -Dcode-audits ``` -------------------------------- ### Configure Kotlin Maven Plugin for Parameter Names Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/mapping.adoc For Kotlin users, ensure the Maven build includes parameter names in the bytecode by adding this configuration to the Kotlin Maven plugin. ```xml true ``` -------------------------------- ### Sample Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $sample stage randomly selects the specified number of documents from the input. ```APIDOC ## Sample Stage ### Description Randomly selects the specified number of documents from the input. ### Method Signature `Sample.sample(long)` ``` -------------------------------- ### Basic Morphia Query Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/quicktour.adoc Fetches all entities of a specified class from the database. For large result sets, consider using `iterator()` directly instead of `toList()` to avoid memory issues. ```java final Query query = datastore.find(Employee.class); final List employees = query.iterator().toList(); ``` -------------------------------- ### Projection with Include and Limit Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/queries.adoc Retrieve only specific fields from documents and limit the number of results. Note the warning about saving projected objects. ```java ContainsRenamedFields user = new ContainsRenamedFields("Frank", "Zappa"); datastore.save(user); ContainsRenamedFields found = datastore .find(ContainsRenamedFields.class) .iterator(new FindOptions() .projection().include("first_name") .limit(1)) .tryNext(); assertNotNull(found.firstName); assertNull(found.lastName); ``` -------------------------------- ### Export Morphia Service with Java Modules Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/configuration.adoc When using Java modules, export your custom Morphia service provider in the module-info.java file to make it discoverable by Morphia. ```java provides dev.morphia.mapping.codec.MorphiaPropertyCodecProvider with com.foo.MyCodecProvider; ``` -------------------------------- ### Query Methods (2.5 and 3.0) Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/morphia-2.5-3.0-table.adoc Core methods for querying data with Morphia, with common methods across versions 2.5 and 3.0. ```APIDOC ## Query Methods ### Description Methods for executing queries, counting documents, deleting, and modifying data in Morphia. ### Methods (Common to 2.5 and 3.0) - `CriteriaContainer and(Criteria)` - `long count()` - `long count(CountOptions)` - `FieldEnd criteria(String)` - `DeleteResult delete()` - `DeleteResult delete(DeleteOptions)` - `Query disableValidation()` - `Query enableValidation()` - `Map explain()` - `FieldEnd field(String)` - `Query filter(Filter)` - `T findAndDelete()` - `T findAndDelete(FindAndDeleteOptions)` - `T first()` - `String getLoggedQuery()` - `MorphiaCursor iterator()` - `MorphiaKeyCursor keys()` - `T findAndDelete()` - `T first()` - `String getLoggedQuery()` - `MorphiaCursor iterator()` ### Methods (Version Specific or Additional) - `MorphiaCursor execute()` (2.5) - `MorphiaCursor execute(FindOptions)` (2.5) - `Map explain(FindOptions)` (2.5) - `Map explain(ExplainVerbosity)` (2.5) - `Map explain(FindOptions, ExplainVerbosity)` (2.5) - `Query filter(String, Object)` (2.5) - `MorphiaCursor find()` (2.5) - `MorphiaCursor find(FindOptions)` (2.5) - `T first(FindOptions)` (2.5) - `Class getEntityClass()` (2.5) - `MorphiaCursor iterator(FindOptions)` (2.5) - `MorphiaKeyCursor keys(FindOptions)` (2.5) - `Modify modify(UpdateOperations)` (2.5) - `Modify modify(UpdateOperator, UpdateOperator)` (2.5) - `T modify(UpdateOperator, UpdateOperator)` (3.0) - `T modify(ModifyOptions, UpdateOperator)` (3.0) ``` -------------------------------- ### Bucket Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $bucket stage groups input documents into specified buckets based on a specified expression. ```APIDOC ## Bucket Stage ### Description Groups input documents into specified buckets based on a specified expression. ### Method `Bucket.bucket()` ### Endpoint N/A (This is a Java API stage) ### Parameters None directly on the `bucket()` method, parameters are configured within the `Bucket` builder. ### Request Example ```java // Example usage within a Morphia aggregation pipeline aggregationPipeline.addStage(Bucket.bucket().groupBy("$age").addOutput("count", new Document("$sum", 1))); ``` ### Response N/A (This stage groups documents within the pipeline) ``` -------------------------------- ### Add Morphia Snapshot Repository (Gradle) Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/index.adoc Configure this repository in your Gradle build script when working with Morphia snapshot versions. ```groovy repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } } ``` -------------------------------- ### StringExpressions#concat Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Concatenates multiple strings. ```APIDOC ## StringExpressions#concat ### Description Concatenates two or more strings. ### Method `concat(Object value, Object... moreValues)` ### Parameters #### Path Parameters - **value** (Object) - The first string to concatenate. - **moreValues** (Object...) - Additional strings to concatenate. ### Request Example ```json { "example": "StringExpressions.concat(str1, str2, str3)" } ``` ### Response #### Success Response (200) - **result** (String) - The concatenated string. ### Response Example ```json { "example": "concatenated string result" } ``` ``` -------------------------------- ### Facet Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $facet stage allows you to create multiple independent pipelines that run in parallel on the same input documents. ```APIDOC ## Facet Stage ### Description Creates multiple independent pipelines that run in parallel on the same input documents. ### Method `Facet.facet()` ### Endpoint N/A (This is a Java API stage) ### Parameters None directly on the `facet()` method, parameters are configured within the `Facet` builder. ### Request Example ```java // Example usage within a Morphia aggregation pipeline aggregationPipeline.addStage(Facet.facet() .facet("results1", aggregationPipeline1) .facet("results2", aggregationPipeline2)); ``` ### Response N/A (This stage outputs results from parallel pipelines) ``` -------------------------------- ### Add Morphia Snapshot Repository (Maven) Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/index.adoc If you are using a snapshot version of Morphia, add this repository configuration to your Maven pom.xml file. ```xml sonatype-snapshots https://oss.sonatype.org/content/repositories/snapshots true ``` -------------------------------- ### Add Morphia Core Dependency (Gradle) Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/index.adoc Use this declaration in your Gradle build file to include the Morphia core library. Replace `{version}` with the specific version you need. ```groovy dependencies { implementation 'dev.morphia.morphia:morphia-core:{version}' } ``` -------------------------------- ### Array Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Documentation for array aggregation expressions like size, slice, and sortArray. ```APIDOC ## size ### Description Returns the number of elements in an array. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## slice ### Description Returns a subset of an array. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## sortArray ### Description Sorts an array of values in ascending or descending order. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Documents Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $documents stage allows you to construct documents from provided values. ```APIDOC ## Documents Stage ### Description Constructs documents from provided values. ### Method `Documents.documents(DocumentExpression... expressions)` ### Endpoint N/A (This is a Java API stage) ### Parameters - **expressions** (DocumentExpression...) - Required - A variable number of DocumentExpression objects to construct the documents. ### Request Example ```java // Example usage within a Morphia aggregation pipeline aggregationPipeline.addStage(Documents.documents(new Document("field1", "value1"), new Document("field2", 123))); ``` ### Response N/A (This stage outputs constructed documents) ``` -------------------------------- ### Aggregation Pipeline Methods Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/morphia-2.5-3.0-table.adoc Methods for constructing and manipulating aggregation pipelines. ```APIDOC ## Aggregation Pipeline Methods ### Description Methods for building and customizing aggregation pipelines in Morphia. ### Methods - `Aggregation pipeline(Stage)` - `Aggregation pipeline(List)` - `Aggregation planCacheStats()` - `Aggregation project(Projection)` - `Aggregation redact(Redact)` - `Aggregation replaceRoot(ReplaceRoot)` - `Aggregation replaceWith(ReplaceWith)` - `Aggregation sample(long)` - `Aggregation set(AddFields)` - `Aggregation set(Set)` - `Aggregation setWindowFields(SetWindowFields)` - `Aggregation skip(long)` - `Aggregation sort(Sort)` - `Aggregation sortByCount(Expression)` - `List toList()` - `Aggregation unionWith(Class, Stage, Stage)` - `Aggregation unionWith(String, Stage, Stage)` - `Aggregation unset(Unset)` - `Aggregation unwind(Unwind)` ``` -------------------------------- ### Project Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $project stage reshapes each document in the pipeline by including, excluding, or renaming fields. ```APIDOC ## Project Stage ### Description Reshapes each document in the pipeline by including, excluding, or renaming fields. ### Method Signature `Projection.project()` ``` -------------------------------- ### Use Tailable Cursors for Capped Collections Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/queries.adoc Enable tailable cursors for capped collections to receive new documents as they are added. `CursorType.Tailable` is used here. Note that `hasNext()` and `next()` will block until new data is available. ```java datastore.getMapper().map(CappedPic.class); getDs().ensureCaps(); // <1> final Query query = getDs().find(CappedPic.class); final List found = new ArrayList<>(); final MorphiaCursor tail = query.iterator(new FindOptions() .cursorType(CursorType.Tailable)); while(found.size() < 10) { found.add(tail.next()); // <2> } ``` -------------------------------- ### Entity with External EntityListener for @PrePersist Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/life-cycle-methods.adoc Use @EntityListeners to delegate life cycle events to an external class. This is useful for cross-cutting concerns like digital signatures, applied to all entities. ```java @EntityListeners(DigitalSigner.class) public class BankAccount { @Id String id; Date lastUpdated = new Date(); } class DigitalSigner { @PrePersist void prePersist( Object entity, Document document) { document.put("signature", sign(document)); } } ``` -------------------------------- ### GridFSItem Wrapper Class Definition Source: https://github.com/morphiaorg/morphia/blob/master/design/GridFS.adoc Introduces a new wrapper type, GridFSItem, with static methods for storing and retrieving data from GridFS. It supports storing items, streams, and specifying bucket names and options. ```java public class GridFSItem { public static GridFSItem store(T item); public static GridFSItem store(T item, GridFSOptions options); // Potentially leaks mapping information public static GridFSItem store(InputStream stream); public static GridFSItem store(InputStream stream, GridFSOptions options); // Potentially leaks mapping information public static GridFSItem store(String bucket, T item); public static GridFSItem store(String bucket, T item, GridFSOptions options); // Potentially leaks mapping information public T get(); public InputStream stream(); public void delete(); } ``` -------------------------------- ### String Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Documentation for string aggregation expressions like split and strLenBytes. ```APIDOC ## split ### Description Splits a string into an array of substrings by a delimiter. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## strLenBytes ### Description Returns the number of bytes in a string. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Add Morphia Core Dependency (Maven) Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/index.adoc Include this dependency in your Maven project to use the core Morphia library. Ensure you replace `{version}` with the desired Morphia version. ```xml dev.morphia.morphia morphia-core {version} ``` -------------------------------- ### Sort.naturalAscending / Sort.naturalDescending Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/query-filters.adoc Provides methods for natural sorting in ascending or descending order. Natural sorting uses the default order of elements as they are stored in the database. ```APIDOC ## Sort.naturalAscending / Sort.naturalDescending ### Description Provides methods for natural sorting in ascending or descending order. Natural sorting uses the default order of elements as they are stored in the database. ### Method Sort#naturalAscending() Sort#naturalDescending() ### Related MongoDB Operator [$natural](http://docs.mongodb.org/manual/reference/operator/query/natural) ``` -------------------------------- ### Maven Build Lifecycle with Critter Plugin Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/maven-plugin.adoc Illustrates how the critter-maven plugin integrates into the Maven build lifecycle. The plugin runs during the 'process-classes' phase, generating entity model classes before the packaging phase. ```text Maven build └─ compile phase → your entity .class files └─ process-classes phase → critter-maven:generate-models reads entity .class files writes generated entity model class files └─ package phase → all .class files bundled in JAR ``` -------------------------------- ### CurrentOp Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $currentOp stage returns a document detailing the operations currently running on the MongoDB instance. ```APIDOC ## CurrentOp Stage ### Description Returns a document detailing the operations currently running on the MongoDB instance. ### Method `CurrentOp.currentOp()` ### Endpoint N/A (This is a Java API stage) ### Parameters None directly on the `currentOp()` method, parameters are configured within the `CurrentOp` builder. ### Request Example ```java // Example usage within a Morphia aggregation pipeline aggregationPipeline.addStage(CurrentOp.currentOp()); ``` ### Response N/A (This stage outputs information about current operations) ``` -------------------------------- ### Update or Create Document if Missing Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/updating-old.adoc Utilize the `createIfMissing` parameter to update a document if it exists, or create it if it does not. This is useful for ensuring a record is present before or after an operation. ```java ops = datastore .createUpdateOperations(Hotel.class) .inc("stars", 50); //update, if not found create it datastore .updateFirst(datastore .createQuery(Hotel.class) .field("stars").greaterThan(100), ops, true); // creates { "_id" : ObjectId("4c60629d2f1200000000161d"), "stars" : 50 } ``` -------------------------------- ### Declare Wildcard Text Index Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/indexing.adoc Use this syntax to create a text index on all fields with string content in a document. Validation is disabled for this type of index. ```java @Indexes(@Index(fields = @Field(value = "$**", type = TEXT))) ``` -------------------------------- ### Limit and Skip Query Results Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/queries.adoc Paginate query results by skipping a specified number of documents and limiting the number of documents returned. ```java datastore.find(Person.class) .iterator(new FindOptions() .skip(1) .limit(10)) ``` -------------------------------- ### Configure Maven Plugin for Custom Recipes Source: https://github.com/morphiaorg/morphia/blob/master/rewrite/README.md Add your custom recipe module as a plugin dependency in your project's pom.xml to enable it for rewrite. ```xml org.openrewrite.maven rewrite-maven-plugin RELEASE com.yourorg.NoGuavaListsNewArrayList com.yourorg rewrite-recipe-starter 0.1.0-SNAPSHOT ``` -------------------------------- ### Define Partial Indexes with @IndexOptions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/indexing.adoc Configure partial indexes using the 'partialFilter' option within @IndexOptions to index only documents that meet a specific filter expression. ```java @Indexes({@Index(options = @IndexOptions(partialFilter = "{ name : { $exists : true } }"), fields = {@Field(value = "name")})}) public class SomeClass { ... } ``` -------------------------------- ### Stream and Document Conversion Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/morphia-2.5-3.0-table.adoc Methods for streaming query results and converting to BSON Document. ```APIDOC ## Stream and Document Conversion ### Methods - `java.util.stream.Stream stream()` - `abstract java.util.stream.Stream stream()` - `java.util.stream.Stream stream(dev.morphia.query.FindOptions)` - `abstract org.bson.Document toDocument()` ``` -------------------------------- ### Configure Legacy Date Storage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/migrating.adoc Include this option if your application stores date/time data using an older scheme, to ensure compatibility when migrating to newer Morphia versions. ```java .dateStorage(DateStorage.SYSTEM_DEFAULT) ``` -------------------------------- ### Delete Multiple Documents Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/deletes.adoc Use `DeleteOptions` with `multi(true)` to delete all documents matching the query criteria. This is useful when you need to remove multiple records at once. ```java datastore .find(Hotel.class) .filter(gt("stars", 100)) .delete(new DeleteOptions() .multi(true)); ``` -------------------------------- ### Skip Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $skip stage passes the documents that follow the first n documents to the next stage in the pipeline. ```APIDOC ## Skip Stage ### Description Passes the documents that follow the first n documents to the next stage in the pipeline. ### Method Signature `Skip.skip(long)` ``` -------------------------------- ### Set Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $set stage adds new fields to documents. ```APIDOC ## Set Stage ### Description Adds new fields to documents. ### Method Signature `Set.set()` ``` -------------------------------- ### Build Complex AND Query Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/queries.adoc Construct a query with multiple conditions combined using an AND logic. The 'and()' method explicitly groups these conditions. ```java q.filter(and( eq("width", 10), eq("height", 1))); ``` -------------------------------- ### Window Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Provides methods for window-based aggregation operations. ```APIDOC ## WindowExpressions#rank() ### Description Returns the rank of a value within a window partition. ### Method N/A (Java method) ### Parameters None. ``` -------------------------------- ### SetWindowFields Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $setWindowFields stage assigns one or more fields to a document based on the specified window. ```APIDOC ## SetWindowFields Stage ### Description Assigns one or more fields to a document based on the specified window. ### Method Signature `SetWindowFields.setWindowFields()` ``` -------------------------------- ### Perform Basic Text Search Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/text-searches.adoc Execute a basic text search for a given term across all indexed text fields. Ensure the collection has a text index defined and the entity is mapped. ```java mapper.map(Greeting.class); datastore.ensureIndexes(); datastore.save(new Greeting("good morning", "english"), new Greeting("good afternoon", "english"), new Greeting("good night", "english"), new Greeting("good riddance", "english"), new Greeting("guten Morgen", "german"), new Greeting("guten Tag", "german"), new Greeting("gute Nacht", "german")); List good = datastore.find(Greeting.class) .filter(text("good")) .iterator(new FindOptions() .sort(ascending("_id"))) .toList(); Assert.assertEquals(4, good.size()); ``` -------------------------------- ### PlanCacheStats Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $planCacheStats aggregation stage returns information from the query plan cache. ```APIDOC ## PlanCacheStats Stage ### Description Returns information from the query plan cache. ### Method Signature `PlanCacheStats.planCacheStats()` ``` -------------------------------- ### Add Morphia Annotations Dependency (Gradle) Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/index.adoc Include this Gradle dependency if your project only needs Morphia's mapping annotations. Update `{version}` to the required version. ```groovy dependencies { implementation 'dev.morphia.morphia:morphia-annotations:{version}' } ``` -------------------------------- ### Mathematical Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Documentation for mathematical aggregation expressions like sqrt, sin, and sinh. ```APIDOC ## sqrt ### Description Returns the positive square root of a number. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## sin ### Description Returns the trigonometric sine of an angle. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## sinh ### Description Returns the hyperbolic sine of a number. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Perform Multiple Update Operations Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/updating-old.adoc Combine multiple update operations into a single command for efficiency. Note that applying conflicting operations to the same property will result in an error. ```java //set city to Ottawa and increment stars by 1 ops = datastore .createUpdateOperations(Hotel.class) .set("city", "Ottawa") .inc("stars"); datastore.update(updateQuery, ops); //if you perform multiple operations in one command on the same property, results will vary ops = datastore .createUpdateOperations(Hotel.class) .inc("stars", 50) .inc("stars"); //increments by 1 ops = datastore .createUpdateOperations(Hotel.class) .inc("stars") .inc("stars", 50); //increments by 50 //you can't apply conflicting operations to the same property ops = datastore .createUpdateOperations(Hotel.class) .set("stars", 1) .inc("stars", 50); //causes error ``` -------------------------------- ### AccumulatorExpressions#min Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Calculates the minimum value from a set of input values. ```APIDOC ## AccumulatorExpressions#min ### Description Calculates the minimum value from a set of input values. ### Method AccumulatorExpressions#min(Object, Object...) ### Endpoint N/A (Java SDK method) ### Parameters * **Object** - The first input value. * **Object...** - A variable number of subsequent input values. ### Request Example ```java // Example usage within Morphia aggregation pipeline aggregation.min(field1, field2, field3) ``` ### Response * **N/A** - Returns an aggregation expression object. ``` -------------------------------- ### Add morphia-kotlin Dependency (Gradle) Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/kotlin.adoc Add this declaration to your Gradle build file to integrate the `morphia-kotlin` module for improved Kotlin compatibility. ```groovy dependencies { compile 'dev.morphia.morphia:morphia-kotlin:{version}' } ``` -------------------------------- ### Delete Documents with Options Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/quicktour.adoc Deletes documents from the database based on a filter. Use DeleteOptions to specify whether to delete multiple documents; by default, only the first match is deleted. ```java datastore.find(Employee.class) .filter(Filters.gt("salary", 100000)) .delete(new DeleteOptions() .multi(true)); ``` -------------------------------- ### IndexStats Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $indexStats aggregation stage returns statistics about the indexes of a collection. ```APIDOC ## IndexStats Stage ### Description Returns statistics about the indexes of a collection. ### Method Signature `IndexStats.indexStats()` ``` -------------------------------- ### Match Stage Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-stages.adoc The $match stage selects the documents that meet the specified condition. ```APIDOC ## Match Stage ### Description Selects the documents that meet the specified condition. ### Method Signature `Match.match(Filter...)` ``` -------------------------------- ### Expressions#meta Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Returns metadata about the query results. ```APIDOC ## Expressions#meta ### Description Returns metadata about the query results. ### Method Expressions#meta() Expressions#meta(MetadataKeyword) Meta#indexKey(String) Meta#searchHighlights(String) Meta#searchScore(String) Meta#textScore(String) ### Endpoint N/A (Java SDK methods) ### Parameters * **MetadataKeyword** - Specifies the type of metadata to retrieve. * **String** - Field name for specific metadata operations. ### Request Example ```java // Example usage within Morphia aggregation pipeline aggregation.meta() aggregation.meta(MetadataKeyword.LANGUAGE) // Using Meta class for specific metadata Meta.indexKey("myIndex") Meta.searchHighlights("myField") Meta.searchScore("myField") Meta.textScore("myField") ``` ### Response * **N/A** - Returns an aggregation expression object or metadata object. ``` -------------------------------- ### Set Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Documentation for set aggregation expressions like setIsSubset, setUnion, and setIntersection. ```APIDOC ## setIsSubset ### Description Checks if one set is a subset of another set. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## setUnion ### Description Returns a set that consists of all the distinct elements from all the input sets. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ## setIntersection ### Description Returns a set that consists of the common elements found in all the input sets. ### Method N/A (Expression) ### Endpoint N/A (Expression) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### WindowExpressions.integral Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Calculates the integral of a value over a window. ```APIDOC ## integral(Object) ### Description Computes the integral of a numeric expression over the documents in a window. ### Method `integral(Object expression)` ### Parameters - **expression** (Object) - The numeric expression to integrate. ### Request Example ```java WindowExpressions.integral(fieldValue) ``` ### Response Returns the integral of the expression over the window. ``` -------------------------------- ### Data Size Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Includes expressions to determine the size of data in BSON format. ```APIDOC ## Data Size Expressions ### Description Includes expressions to determine the size of data in BSON format. ### Methods - `DataSizeExpressions#binarySize(Object)` - `DataSizeExpressions#bsonSize(Object)` ``` -------------------------------- ### Type Expressions Source: https://github.com/morphiaorg/morphia/blob/master/docs/modules/ROOT/pages/aggregation-expressions.adoc Provides methods for type conversion within aggregation pipelines. ```APIDOC ## toBool(Object value) ### Description Converts a value to a boolean. ### Method `toBool` ### Parameters #### Path Parameters - **value** (Object) - The value to convert. ### Request Example ```json { "$toBool": } ``` ### Response #### Success Response (200) - **boolean** (boolean) - The boolean representation of the value. ``` ```APIDOC ## toDate(Object value) ### Description Converts a value to a Date object. ### Method `toDate` ### Parameters #### Path Parameters - **value** (Object) - The value to convert. ### Request Example ```json { "$toDate": } ``` ### Response #### Success Response (200) - **Date** (Date) - The Date object representation of the value. ``` ```APIDOC ## toDecimal(Object value) ### Description Converts a value to a Decimal128 type. ### Method `toDecimal` ### Parameters #### Path Parameters - **value** (Object) - The value to convert. ### Request Example ```json { "$toDecimal": } ``` ### Response #### Success Response (200) - **Decimal128** (Decimal128) - The Decimal128 representation of the value. ```