$substr (aggregation)

Definition

  • $substr

Deprecated since version 3.4: $substr is now an alias for$substrBytes.

Returns a substring of a string, starting at a specified indexposition and including the specified number of characters. The indexis zero-based.

$substr has the following syntax:

  1. { $substr: [ <string>, <start>, <length> ] }

The arguments can be any valid expression as long as long as the first argumentresolves to a string, and the second and third arguments resolve tointegers. For more information on expressions, seeExpressions.

Behavior

If <start> is a negative number, $substr returns anempty string "".

If <length> is a negative number, $substr returns asubstring that starts at the specified index and includes the rest ofthe string.

$substr only has a well-defined behavior for strings of ASCII characters.

Example

Consider an inventory collection with the following documents:

  1. { "_id" : 1, "item" : "ABC1", quarter: "13Q1", "description" : "product 1" }
  2. { "_id" : 2, "item" : "ABC2", quarter: "13Q4", "description" : "product 2" }
  3. { "_id" : 3, "item" : "XYZ1", quarter: "14Q2", "description" : null }

The following operation uses the $substr operatorto separate the quarter value into a yearSubstring and aquarterSubstring:

  1. db.inventory.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. item: 1,
  7. yearSubstring: { $substr: [ "$quarter", 0, 2 ] },
  8. quarterSubtring: { $substr: [ "$quarter", 2, -1 ] }
  9. }
  10. }
  11. ]
  12. )

The operation returns the following results:

  1. { "_id" : 1, "item" : "ABC1", "yearSubstring" : "13", "quarterSubtring" : "Q1" }
  2. { "_id" : 2, "item" : "ABC2", "yearSubstring" : "13", "quarterSubtring" : "Q4" }
  3. { "_id" : 3, "item" : "XYZ1", "yearSubstring" : "14", "quarterSubtring" : "Q2" }