Skip to content

P2: Usage examples moved to appropriate pages #624

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Mar 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 36 additions & 11 deletions source/command.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,24 @@
Run a Command
=============

You can run all raw database operations using the
.. facet::
:name: genre
:values: reference

.. meta::
:keywords: database, call, admin, administration, meta, backend, configure
:description: Learn about how to run database commands in the {+driver-long+}.

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to run raw database operations using the
``MongoDatabase.runCommand()`` method. A raw database operation is a
command you can execute directly on the {+mdb-server+} CLI. These
commands include administrative and diagnostic tasks, such as fetching
Expand All @@ -28,17 +45,16 @@ By default, ``runCommand`` returns an object of type
can specify a return type for ``runCommand()`` as an optional second
parameter.

Example
-------
Run Command Example: Full File
------------------------------

In the following sample code, we send the ``dbStats`` command to request
statistics from a specific MongoDB database.

.. include:: /includes/connect-guide-note.rst

.. literalinclude:: /includes/usage-examples/code-snippets/Command.java
:language: java

.. literalinclude:: /includes/RunCommand.java
:language: java

When you run the preceding command, you should see output similar to the
following:
Expand All @@ -50,9 +66,18 @@ following:

.. include:: /includes/legacy-redirect.rst

For additional information on the classes and methods mentioned on this
page, see the following resources:
Additional Information
----------------------

API Documentation
~~~~~~~~~~~~~~~~~

For more information about the method used to run database commands, see the following API documentation:

- `runCommand() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#runCommand(org.bson.conversions.Bson)>`__

Server Manual Entries
~~~~~~~~~~~~~~~~~~~~~

- `runCommand() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html#runCommand(org.bson.conversions.Bson)>`__ API Documentation
- :manual:`Database Commands </reference/command/>` Server Manual Entry
- :manual:`dbStats </reference/command/dbStats/>` Server Manual Entry
- :manual:`Database Commands </reference/command/>`
- :manual:`dbStats </reference/command/dbStats/>`
22 changes: 13 additions & 9 deletions source/crud/read-operations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,23 @@ Read Operations
:caption: Read Operations

Retrieve Data </crud/read-operations/retrieve>
Data from a Cursor </crud/read-operations/cursor>
Access Data from a Cursor </crud/read-operations/cursor>
Sort Results </crud/read-operations/sort>
Skip Returned Results </crud/read-operations/skip>
Limit Returned Results </crud/read-operations/limit>
Specify Fields to Return </crud/read-operations/project>
Count Documents </crud/read-operations/count>
Retrieve Distinct Values of a Field </crud/read-operations/distinct>
Geospatial Data </crud/read-operations/geo>
Search Text </crud/read-operations/text>

- :doc:`/crud/read-operations/retrieve`
- :doc:`/crud/read-operations/cursor`
- :doc:`/crud/read-operations/sort`
- :doc:`/crud/read-operations/skip`
- :doc:`/crud/read-operations/limit`
- :doc:`/crud/read-operations/project`
- :doc:`/crud/read-operations/geo`
- :doc:`/crud/read-operations/text`
- :ref:`Retrieve <java-fundamentals-retrieve-data>`
- :ref:`Access Data From a Cursor <java-fundamentals-cursor>`
- :ref:`Sort Results <java-fundamentals-sort>`
- :ref:`Skip Returned Results <java-fundamentals-skip>`
- :ref:`Limit the Number of Returned Results <java-fundamentals-limit>`
- :ref:`Specify Which Fields to Return <java-fundamentals-project>`
- :ref:`Count Documents <java-count>`
- :ref:`Retrieve Distinct Values of a Field <java-usage-distinct>`
- :ref:`Search Geospatially <java-geo-search>`
- :ref:`Search Text <java-fundamentals-search-text>`
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
.. _java-usage-count:
.. _java-count:

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: per the renaming guidance, leave old anchors in place
Q: will there be redirects for moving these pages around?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved this tag down to the Count Documents Example: Full File, so that anyone referencing it will still be taking to the example.

===============
Count Documents
===============

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: count, number, size, collection, code example
:description: Learn about how to count the number of documents in a collection in the {+driver-long+}.

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

There are two instance methods in the ``MongoCollection`` class that you can
call to count the number of documents in a collection:
In this guide, you can learn how to count the number of documents in your
MongoDB collections. There are two instance methods in the
``MongoCollection`` class that you can call to count the number of documents in
a collection:

- ``countDocuments()`` returns the number of documents in the collection
that match a specified query. If you specify an empty query filter,
Expand Down Expand Up @@ -74,17 +91,19 @@ specify the behavior of the call:

Both methods return the number of matching documents as a ``long`` primitive.

Example
-------
.. _java-usage-count:

Count Documents Example: Full File
----------------------------------

.. include:: /includes/crud/example-intro.rst

The following example estimates the number of documents in the
``movies`` collection in the ``sample_mflix`` database, and then returns
an accurate count of the number of documents in the ``movies``
collection with ``Canada`` in the ``countries`` field.

.. include:: /includes/connect-guide-note.rst

.. literalinclude:: /includes/usage-examples/code-snippets/CountDocuments.java
.. literalinclude:: /includes/crud/CountDocuments.java
:language: java

If you run the preceding sample code, you should see output that looks something
Expand All @@ -98,10 +117,21 @@ like this (exact numbers can vary depending on your data):

.. include:: /includes/legacy-redirect.rst

For additional information on the classes and methods mentioned on this
page, see the following API Documentation:
Additional Information
----------------------

API Documentation
~~~~~~~~~~~~~~~~~

For more information about the classes and methods used to count documents, see the following API documentation:

- `countDocuments() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#countDocuments()>`__
- `estimatedDocumentCount() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#estimatedDocumentCount()>`__
- `CountOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/CountOptions.html>`__
- `EstimatedDocumentCountOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/model/EstimatedDocumentCountOptions.html>`__

Server Manual Entries
~~~~~~~~~~~~~~~~~~~~~

- :manual:`db.collection.countDocuments() </reference/method/db.collection.countDocuments/>`
- :manual:`db.collection.estimatedDocumentCount() </reference/method/db.collection.estimatedDocumentCount/>`
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,28 @@
Retrieve Distinct Values of a Field
===================================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: find, distinct, unique, discrete, code example
:description: Learn about how to retrieve the number of distinct values of a field in the {+driver-long+}.

You can retrieve a list of distinct values for a field across a
collection by calling the ``distinct()`` method on a ``MongoCollection``
object. Pass the document field name as the first parameter and the class
you want to cast the results to as the second parameter as shown below:
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

Overview
--------

In this guide, you can learn how to retrieve a list of distinct values for a
field across a collection by calling the ``distinct()`` method on a
``MongoCollection`` object. Pass the document field name as the first parameter
and the class you want to use for the results as the second parameter, as shown
below:

.. code-block:: java

Expand Down Expand Up @@ -48,7 +64,7 @@ match movies that include "Carl Franklin" as one of the values in the

.. include:: /includes/connect-guide-note.rst

.. literalinclude:: /includes/usage-examples/code-snippets/Distinct.java
.. literalinclude:: /includes/crud/Distinct.java
:language: java

When you run the example, you should see output that reports each distinct
Expand All @@ -66,7 +82,7 @@ which resembles the following:

.. include:: /includes/legacy-redirect.rst

For additional information on the classes and methods mentioned on this
For more information about the classes and methods mentioned on this
page, see the following resources:

- `distinct() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#distinct(java.lang.String,java.lang.Class)>`__ API Documentation
Expand Down
8 changes: 8 additions & 0 deletions source/crud/read-operations/geo.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
.. _java-geo-search:

===================
Search Geospatially
===================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: find, geo, geographic, location, locale, coordinate, latitude, longitude, code example
:description: Learn about how to search geospatial data in the {+driver-long+}.

.. contents:: On this page
:local:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Runs a database command by using the Java driver

package usage.examples;
package org.example;

import org.bson.BsonDocument;
import org.bson.BsonInt64;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
// Runs count operations on a collection by using the Java driver
/**
* This file demonstrates how to open a change stream by using the Java driver.
* It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens
* to change events in the "movies" collection. The code uses a change stream with a pipeline
* to only filter for "insert" and "update" events.
*/

package usage.examples;

Expand All @@ -24,19 +29,13 @@ public static void main(String[] args) {

Bson query = eq("countries", "Spain");

try {
// Retrieves and prints the estimated number of documents in the collection
long estimatedCount = collection.estimatedDocumentCount();
System.out.println("Estimated number of documents in the movies collection: " + estimatedCount);

// Retrieves and prints the number of documents with a "countries" value of "Spain"
long matchingCount = collection.countDocuments(query);
System.out.println("Number of movies from Spain: " + matchingCount);

// Prints a message if any exceptions occur during the operations
} catch (MongoException me) {
System.err.println("An error occurred: " + me);
}
// Retrieves and prints the estimated number of documents in the collection
long estimatedCount = collection.estimatedDocumentCount();
System.out.println("Estimated number of documents in the movies collection: " + estimatedCount);

// Retrieves and prints the number of documents with a "countries" value of "Spain"
long matchingCount = collection.countDocuments(query);
System.out.println("Number of movies from Spain: " + matchingCount);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,13 @@ public static void main(String[] args) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");

try {
// Retrieves the distinct values of the "year" field present in documents that match the filter
DistinctIterable<Integer> docs = collection.distinct("year", Filters.eq("directors", "Carl Franklin"), Integer.class);
MongoCursor<Integer> results = docs.iterator();

// Prints the distinct "year" values
while(results.hasNext()) {
System.out.println(results.next());
}

// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("An error occurred: " + me);
// Retrieves the distinct values of the "year" field present in documents that match the filter
DistinctIterable<Integer> docs = collection.distinct("year", Filters.eq("directors", "Carl Franklin"), Integer.class);
MongoCursor<Integer> results = docs.iterator();

// Prints the distinct "year" values
while(results.hasNext()) {
System.out.println(results.next());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* to only filter for "insert" and "update" events.
*/

package usage.examples;
package org.example;

import java.util.Arrays;
import java.util.List;
Expand All @@ -20,6 +20,7 @@
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.changestream.FullDocument;
import com.mongodb.client.model.Aggregates;

public class Watch {
public static void main( String[] args ) {
Expand All @@ -33,21 +34,21 @@ public static void main( String[] args ) {

// Creates instructions to match insert and update operations
List<Bson> pipeline = Arrays.asList(
Aggregates.match(
Filters.in("operationType",
Arrays.asList("insert", "update"))));
Aggregates.match(
Filters.in("operationType",
Arrays.asList("insert", "update"))));

// Creates a change stream that receives change events for the specified operations
ChangeStreamIterable<Document> changeStream = database.watch(pipeline)
.fullDocument(FullDocument.UPDATE_LOOKUP);
.fullDocument(FullDocument.UPDATE_LOOKUP);

final int[] numberOfEvents = {0};

// Prints a message each time the change stream receives a change event, until it receives two events
changeStream.forEach(event -> {
System.out.println("Received a change to the collection: " + event);
System.out.println("Received a change to the collection: " + event);
if (++numberOfEvents[0] >= 2) {
System.exit(0);
System.exit(0);
}
});
}
Expand Down
Loading
Loading