How to use MongoDB queries to increase your DBA expertise

Question: We’ve started managing a monitoring system with an API interface –  generating output from a MongoDB database. We have no knowledge of MongoDB and just need a quick primer on some basics . In the meanwhile we are organising some training .

Answer: I received this request from some colleagues – and I’m finding as mindshare moves towards MongoDB there is a gap in DBA’s knowledge on the nosql paradigm. But you have to start somewhere , and my recommendation was to download one of the MongoDB Atlas databases – e.g sample_airbnb – and play around with some of the commands.

Sample_airbnb

–return all Collections in db
db.getCollectionNames();

–return all rows in a collection
db.listingsAndReviews.find();

From the MongoDB documentation “The aggregation pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into aggregated results”

–return only 2 columns – example of using an aggregate
db.listingsAndReviews.aggregate({$project : {_id : 1 , property_type : 1}}).pretty();
db.listingsAndReviews.aggregate({$project : {_id : 1 , calendar_last_scraped : 1}})
db.listingsAndReviews.aggregate({$project : {_id : 1 , calendar_last_scraped : 1}}).pretty();

–return a specific row with a value 
db.listingsAndReviews.find({_id:”10091713″}).pretty();
db.listingsAndReviews.find({_id:”10091713″}).count();
db.listingsAndReviews.find({_id :{ $eq:”10091713″}}).pretty();

db.listingsAndReviews.find({“name”: /Rib/});

A  MongoDB view is the result of a stored aggregation on a collection, which database users can query just as if it were a materialized collection object.Some benefits include simplify coding
and decouple db & app

Views typically are the result of groupings and aggregation pipeline Data aggregations provide a summary of the underlying doc & collections

–added 7 days using the aggregate function
db.listingsAndReviews.aggregate({$project : {_id : 1 , calendar_last_scraped : 1, Plus_7_days :{ $add: [ “$calendar_last_scraped”, 7*24*60*60000 ] }}})

–create a view
db.createView(“PlusDays”,”listingsAndReviews”,{$project : {_id : 1 , calendar_last_scraped : 1, Plus_7_days :{ $add: [ “$calendar_last_scraped”, 7*24*60*60000 ] }}});

–view contents of collection
db.PlusDays.find();

–get count
db.PlusDays.find().count();

–drop the PlusDays view (collection)

db.PlusDays.drop();

I’ll add some more variations tommorow

Author: Rambler

Leave a Reply

Discover more from ciquery

Subscribe now to keep reading and get access to the full archive.

Continue reading