MongoDB – Natural sort

One of the most common problems with databases are sorting. Let’s see an simple example: we use MySQL/MariaDB and have table with some data. We want to sort this data. Everything is ok if we use only values in the same type in field, for example numeric (maybe some amount?), strings (titles), dates, keys etc. But what if field is custom, user-typed data and may contain many types? In that case, we have big problem, because standard sorting is not enought, it will not work. Example, value: “11”, “1”, “2”, “3”, “2a” will be sorted in order: 1, 11, 2, 2a, 3, not as we expected i.e. 1, 2, 2a, 3, 11. The solution is to use natural sorting.

Continue reading “MongoDB – Natural sort”

Laravel Eloquent: MongoDB relations

Laravel MongoDB

Laravel offers very complex Eloquent – ORM simple to use, but with a lot of options. One of them is relations support. We can define several types of relations between our models and then use them to simplify get the data. Relations are also support by MongoDB extension for Eloquent, which is available on GitHub. Sometimes it may be difficult to use because of some issues with ObjectId and BSON. Let’s see how it can be solved.

Continue reading “Laravel Eloquent: MongoDB relations”

GROUP BY ($group) in MongoDB

Mongodb is not relational database, but we sometimes want to use functions similar from such databases. I wrote about JOINs in Mongo few weeks ago, but it isn’t only one option. Second and very interesting is grouping – something like GROUP BY in for example MySQL database. Do we really need grouping in Mongo? Maybe yes, maybe no, but I must implement such option for one of application modules. It isn’t difficult and we can do this very simply. Again, I will use examples from PHP and mongodb extension for this language – code should be very similar in other languages.

Continue reading “GROUP BY ($group) in MongoDB”

PHP/Mongo – Using JOIN in queries

I’ve written one post about MongoDB and PHP about creating nested set model in this database, but there is another interesting topic: using JOINs in mongo queries. Sorry, wh… what? Joining tables in non-relational database? Yes, it’s possible and we can do this to collect much more data in only one, but more complicated query. Let’s start to see how we can achieve this.

Continue reading “PHP/Mongo – Using JOIN in queries”

PHP/Mongo – Nested set model

Last time I created some structure for linking different elements from similar groups. This project needed high performance and easy way to get elements hierarchy, but changes are not often. After consideration I decided to implement nested set tree model to do this. All is based on PHP and use Mongo database and I would like to show you some basis operations with that. It can be helful in some cases, and that model is very efficient in read operations.

Continue reading “PHP/Mongo – Nested set model”