Docs Menu
Docs Home
/ / /
Scala
/

Projections

On this page

  • Inclusion
  • Exclusion
  • Exclusion of _id Field
  • Array Element Match with a Specified Filter
  • Array Element Match with an Implicit Filter
  • Slice
  • Text Score
  • Combining Projections

The Projections class provides static factory methods for the MongoDB projection operators. Each method returns an instance of the Bson type, which can in turn be passed to any method that expects a projection.

You can import the methods of the Projections class statically, as shown in the following code:

import org.mongodb.scala.model.Projections._

The examples in this guide assume this static import.

By default, all fields of each document are included in the results. To specify the inclusion of one or more fields, which implicitly excludes all other fields except _id, use the include() method.

The following example includes the quantity field and, implicitly, the _id field:

include("quantity")

The following example includes the quantity and totalAmount fields and, implicitly, the _id field:

include("quantity", "totalAmount")

To specify the exclusion of one or more fields, which implicitly includes all other fields, use the exclude() method.

The following example excludes the quantity field:

exclude("quantity")

The following example excludes the quantity and totalAmount fields:

exclude("quantity", "totalAmount")

To specify the exclusion of the _id field, use the excludeId() method:

excludeId()

This is equivalent to the following code:

exclude("_id")

To specify a projection that includes only the first element of an array that matches a supplied query filter, use the elemMatch() method that takes a field name and a filter.

The following example projects the first element of the orders array field, where the quantity field is greater than 3:

elemMatch("orders", Filters.gt("quantity", 3))

To specify a projection that includes only the first element of an array that matches the filter supplied as part of the query, use the elemMatch() method that takes just a field name.

The following example projects the first element of the orders array that matches the query filter:

elemMatch("orders")

To project a slice of an array, use one of the slice() methods.

The following example projects the first 7 elements of the tags array:

slice("tags", 7)

The following example skips the first 2 elements of the tags array and projects the next 5:

slice("tags", 2, 5)

To specify a projection of the score of a $text query, use the metaTextScore() method to specify the name of the projected field.

The following example projects the text score as the value of the score field:

metaTextScore("score")

To combine multiple projections, use the fields method.

The following example includes the quantity and totalAmount fields and excludes the _id field:

fields(include("quantity", "totalAmount"), excludeId())

Back

Filters