Skip to content
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

DOCSP-41135: Specify Fields #8

Merged
merged 7 commits into from
Jul 18, 2024
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
68 changes: 68 additions & 0 deletions source/includes/read/project.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package org.example
import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Projections
import com.mongodb.kotlin.client.MongoClient
import org.bson.codecs.pojo.annotations.BsonId
import org.bson.types.ObjectId

// start-data-class
data class Restaurant(
@BsonId
val id: ObjectId? = null,
val name: String,
val borough: String,
val cuisine: String
)
// end-data-class

fun main() {
val uri = "<connection string URI>"

val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.retryWrites(true)
.build()

val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_restaurants")
val collection = database.getCollection<Restaurant>("restaurants")

// start-project
val projection = Projections.fields(
Projections.include(
Restaurant::name.name,
Restaurant::cuisine.name,
Restaurant::borough.name
)
)

val results = collection
.find(eq(Restaurant::name.name, "Emerald Pub"))
.projection(projection)

results.forEach { result ->
println(result)
}
// end-project

// start-project-exclude
val projection = Projections.fields(
Projections.excludeId(),
Projections.include(
Restaurant::name.name,
Restaurant::cuisine.name,
Restaurant::borough.name
)
)

val results = collection
.find(eq(Restaurant::name.name, "Emerald Pub"))
.projection(projection)

results.forEach { result ->
println(result)
}
// end-project-exclude
}
1 change: 1 addition & 0 deletions source/read.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Read Data from MongoDB
:maxdepth: 1

/read/count
/read/project

Overview
--------
Expand Down
127 changes: 127 additions & 0 deletions source/read/project.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
.. _kotlin-sync-project:

========================
Specify Fields To Return
========================

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

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

.. meta::
:keywords: read, filter, project, select

Overview
--------

In this guide, you can learn how to specify which fields to return from a read
operation by using a **projection**. A projection is a document that specifies
which fields MongoDB returns from a query.

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
:atlas:`Get Started with Atlas </getting-started>` guide.

The documents in this collection are modeled by the following {+language+} data class:

.. literalinclude:: /includes/read/project.kt
:start-after: start-data-class
:end-before: end-data-class
:language: kotlin
:copyable:

Projection Types
----------------

You can use a projection to specify which fields to include in a return
document, or to specify which fields to exclude.

When specifying certain fields to include in a projection, all other fields are implicitly
excluded (except the ``_id`` field, which is included by default). You cannot combine
inclusion and exclusion statements in a single projection, unless you are excluding the
``_id`` field.

To remove the ``_id`` field from the returned document, you must
:ref:`explicitly exclude it <kotlin-sync-project-exclude-id>`.

Specify Fields to Include
~~~~~~~~~~~~~~~~~~~~~~~~~

Use the following syntax to specify the fields to include in the result:

.. code-block:: kotlin

val projection = Projection.fields(
Projections.include(<fieldName1>, <fieldName2>, ...)
)

The following example uses the ``find()`` method to find all restaurants with
the ``name`` field value of ``"Emerald Pub"``. It then uses a projection to
return only the ``name``, ``cuisine``, and ``borough`` fields of the returned
documents.

.. io-code-block::
:copyable: true

.. input:: /includes/read/project.kt
:start-after: start-project
:end-before: end-project
:language: kotlin
:dedent:

.. output::
:visible: false

Restaurant(id=5eb3d668b31de5d588f429e2, name=Emerald Pub, borough=Manhattan, cuisine=American)
Restaurant(id=5eb3d668b31de5d588f432dd, name=Emerald Pub, borough=Queens, cuisine=American)

.. _kotlin-sync-project-exclude-id:

Exclude the ``_id`` Field
~~~~~~~~~~~~~~~~~~~~~~~~~

When specifying fields to include, you can also exclude the ``_id`` field from
Copy link

@shuangela shuangela Jul 12, 2024

Choose a reason for hiding this comment

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

Q: Can you only exclude the _id field when specifying fields to include, or can you exclude just the _id field without using any includes statements?

the returned document.

The following example runs the same query as the preceding example, but
excludes the ``_id`` field from the projection:

.. io-code-block::
:copyable: true

.. input:: /includes/read/project.kt
:start-after: start-project-exclude
:end-before: end-project-exclude
:language: kotlin
:dedent:

.. output::
:visible: false

Restaurant(id=null, name=Emerald Pub, borough=Manhattan, cuisine=American)
Restaurant(id=null, name=Emerald Pub, borough=Queens, cuisine=American)

Additional Information
----------------------

To learn more about projections, see the :manual:`Project Fields guide
</tutorial/project-fields-from-query-results/>` in the MongoDB Server Manual.

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

To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:

- `find() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/find.html>`__
- `projection() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-find-iterable/projection.html>`__
Loading