Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MongoDB Tips & Tricks: Handling $type and Arrays

DZone's Guide to

MongoDB Tips & Tricks: Handling $type and Arrays

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

According to Thomas Zahn, Co-Founder and CEO of 3T Software Labs, coming to MongoDB from a relational database background is a relief. In this recent article from the 3T Software Labs Blog, he points to the flexibility and dynamic nature of MongoDB as big selling points, as well as the JSON-based query language. However, that's not to say that MongoDB is completely free of cryptic design choices that may leave developers puzzled. 

In particular, Zahn's article focuses on MongoDB's $type query operator, which allows queries to filter by a certain types (only return Strings, for example). However, when it comes to Arrays, $type is a little strange: rather than returning fields that contain Arrays, it searches the individual elements of a field's Array for Arrays. In other words, an $type query for Arrays only finds two-dimensional Arrays - not exactly intuitive.

Zahn explores a number of solutions to this problem - reverting to JavaScript for a workaround, for example - and weighs the pros and cons (and performance drawbacks) of each. Also, Zahn takes a look at the reasons one might have for seeking out Arrays; they can have a major impact on certain operations in terms of performance, and Zahn explores those scenarios.

It's not that Zahn is out to smear the name of MongoDB - as is made clear at the start of his article, he's pretty fond of it - but some problems just seem so simple to fix:

Overall, I think it would be really great to have a dedicated $isArray query operator. The peculiar (and at times inconsistent) way arrays are handled by the search engine currently make it unnecessarily complex to guard one’s update queries against the tricky intricacies of arrays.

Check out Zahn's full article for details on how to avoid Array mishaps with $type in MongoDB.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}