find-documents

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: session, entitymanager -->

Find Documents

Overview

In this guide, you can learn how to use the MongoDB Extension for Hibernate ORM to run a database query to retrieve documents from a MongoDB collection.

To query your MongoDB data, call the createQuery() method on a session or an entity manager. Then, specify your query in a Hibernate Query Language (HQL) or Jakarta Persistence Query Language (JPQL) statement.

Retrieve All Documents

To retrieve all documents from a collection, pass a select statement to the createQuery() method. In this statement, specify the entity that represents the collection you want to query.

The following example retrieves the title values of all documents from the sample_mflix.movies collection by querying the Movie entity:

Session

var allDocs = session.createQuery("select title from Movie", String.class)
                           .getResultList();
for (var t : allDocs) {
    System.out.println("Title: " + t);
}

Output:

Title: A Corner in Wheat
Title: Gertie the Dinosaur
Title: The Perils of Pauline
Title: Civilization
Title: Where Are My Children?
...

Retrieve Matching Documents

To retrieve documents that match specific criteria, pass a select statement with a where clause to the createQuery() method. In this statement, specify the entity that represents the collection you want to query and the matching criteria.

The following example retrieves documents that have a title value of “Romeo and Juliet” from the sample_mflix.movies collection:

Session

var matchingDocs = session.createQuery("from Movie where title = :t", Movie.class)
                          .setParameter("t", "Romeo and Juliet")
                          .getResultList();
for (var m : matchingDocs) {
    System.out.println("Title: " + m.getTitle() + ", Year: " + m.getYear());
}

Output:

Title: Romeo and Juliet, Year: 1936
Title: Romeo and Juliet, Year: 1968

Retrieve One Document

To retrieve a single document that matches specific criteria, chain the getSingleResult() method to the createQuery() method.

The following example retrieves a single document that has a title value of “Best in Show” from the sample_mflix.movies collection:

Session

var singleResult = session.createQuery("from Movie where title = :t", Movie.class)
                          .setParameter("t", "Best in Show")
                          .getSingleResult();
System.out.println("Title: " + singleResult.getTitle() + ", Year: " + singleResult.getYear());

Output:

Title: Best in Show, Year: 2000

Important: NonUniqueResultException Errors

If your query matches multiple documents, the getSingleResult() method throws a NonUniqueResultException error. To avoid this error, ensure that your query matches only one document or [limit your query results](https://www.mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/modify-query-results.md#std-label-hibernate-query-limit to one document.

Run Criteria API Queries

Instead of using HQL or JPQL statements to create query filters, you can use the Jakarta Persistence Criteria API to build type-safe queries programmatically.

To create a query by using the Criteria API, complete the following steps:

  1. Create a CriteriaBuilder object from a session or an entity manager.

  2. Create a CriteriaQuery object from the builder and specify the entity to query.

  3. Use query methods provided by the CriteriaQuery class to specify your query criteria.

Tip:

To learn more about the Criteria API, see Using the Criteria API to Create Queries in the Jakarta EE documentation.

The following example uses the Criteria API to retrieve all documents that have a year value of 1925 from the sample_mflix.movies collection:

Session

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Movie> cq = cb.createQuery(Movie.class);
Root<Movie> movieRoot = cq.from(Movie.class);

cq.select(movieRoot).where(cb.equal(movieRoot.get("year"), 1925));
session.createQuery(cq).getResultList()
    .forEach(m -> System.out.println(m.getTitle()));

Output:

Lady Windermere's Fan
Clash of the Wolves
Grass: A Nation's Battle for Life

Run Native Queries

To run MongoDB queries that are not currently supported by the Hibernate ORM extension, you can pass your query as a MongoDB Query Language (MQL) statement to the createNativeQuery() method.

To learn how to run native queries, see the [Perform Native Queries](https://www.mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/native-queries.md#std-label-hibernate-native-queries guide.

Additional Information

To learn more about performing other operations on your MongoDB data, see the [Perform CRUD Operations](https://www.mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/crud.md#std-label-hibernate-crud guide.

To learn more about using HQL and JPQL to run queries, see A Guide to Hibernate Query Language in the Hibernate ORM documentation.