MongoDB $substrCP Operator Examples
To understand it better, let’s look at some examples of the MongoDB $substrCP operator.
In the following examples, we are working with:
Database: w3wiki
Collection: articles
Documents: three documents that contain the details of the articles in the form of field-value pairs.
Using $substrCP operator Example
Now, displaying the above article’s output by splitting the “publishedon” column details as “publicationmonth” and “publicationyear” by using the below query:
db.articles.aggregate(
[
{
$project: {
articlename: 1,
publicationmonth: { $substrCP: [ "$publishedon", 0, 4 ] },
publicationyear: {
$substrCP: [
"$publishedon", 4, { $subtract: [ { $strLenCP: "$publishedon" }, 4 ] }
]
}
}
}
]
)
Here, “publicationmonth” is following straight syntax and it picks the first 4 characters of “publishedon” column. In “publicationyear”, rest of the characters of “publishedon” are taken. It uses “$subtract” which is used for subtracting the byte index from the length of the string by using $strLenCP.
Output:
MongoDB $substrCP Operator
MongoDB $substrCP Operator extracts a substring from the given string expression.