DEV Community

Rogério Ramos
Rogério Ramos

Posted on

The terrifying mongoDB sintaxe

The main responsibility of experienced Sw Developers is help others and use the gained experience to overcome issues always teaching, learning and sharing.

I want to share a simple thing that make me think about complexity and trade-offs. I co-worker came to me asking for help on a MongoDB aggregate query:

How would I aggregate the data that I need since I am using a NoSQL database?

Can I use my previous SQL knowledge to make it happen?

Well, I think the things could be simpler but not. Look at the example bellow.

I have a series of events happening in my application where a particular event seems to be happening more often than expected. I would like check how often that event happens.

On mongo:

mongo-client-shell> db.orders.aggregate([ 
  { $match: {"event": "order.event.OrderPickedEvent"}} ,
  { $group : { _id: {"event": "$event", "orderNumber": '$orderNumber'}, count: { $sum: 1 } } }, 
  { $sort: {count: -1}}
], 
{allowDiskUse:true}
)

On Postgresql:

psql> select count(*) as total 
  from order 
  where event = "order.event.OrderPickedEvent" 
  group by orderNumber 
  order by total desc;

The question on my mind: Why Mongo make things so weird to not say complex?

Its not natural to the reader.
We are always talking about code clearness, readability and making things simpler. But seems that big player not thing in the same way.

I hope this mini post can help others and maybe sensitize the tool's suppliers to make life easier*.

Top comments (2)

Collapse
 
eduardohitek profile image
Eduardo Hitek

I think this example is not fair with the robustness in using Mongo Aggregation framework. IMHO the great thing about is that you can execute several steps in your data while being at the database side. You're able to perform a lot of transformations and operations just to make sure your application will receive only the data it needs.
The other scenario where the MongoDB syntax makes sense is when you have an array field on your collection. Using the $unwind command, can really make your life easier for querying and transformation.
Give it another try. =]

Collapse
 
habutre profile image
Rogério Ramos • Edited

Hi Eduardo!

Maybe you just misunderstood the goal of this post. I didn’t say mongo is not robust or a good solution for any case, the point here is about the low level and non-fluent sintaxe.

When someone compare with the same query on SQL world is readable and easy to get the point.

My feeling is the MongoDB Inc. put in the Dev’s back the responsibility to explore all possibilities sometimes repetitive and well-known like grouping, summing, etc. They have enough resources to provide a high level sintaxe

Thanks for your point of view and btw I am using Mongo daily but with no so much love