MongoDB $split

In MongoDB, the $split aggregation pipeline operator divides a string into an array of substrings based on a delimiter.

The delimiter is removed from the string, and the substrings are added as elements to the array.

To use $split, you specify the string and the delimiter.

If the delimiter isn’t found in the string, the original string is returned as the only item in the array.

Continue reading

2 Ways to Limit the Documents Returned in MongoDB

When you run queries In MongoDB, you have the option of limiting the documents returned. This is where you specify a maximum number of documents to be returned by the operation.

For example, if an operation would normally return 2,000 documents, but you specify a limit of 1,000, then only 1,000 documents are returned. However, if the operation would only return say, 500 documents, then all 500 are returned (because they don’t breach the 1,000 document limit).

This is a bit like using the TOP clause in SQL Server, or the LIMIT clause in MySQL, MariaDB, PostgreSQL, and SQLite.

Continue reading

MongoDB $setDifference

In MongoDB, the $setDifference aggregation pipeline operator accepts two sets and performs a relative complement of the second set relative to the first. It returns an array containing the elements that only exist in the first set.

$setDifference accepts two arguments, both of which can be any valid expression as long as they each resolve to an array. $setDifference treats the arrays as sets.

Continue reading