mongodb: querying a database from the mongosh

2021-11-25

 | 

~3 min read

 | 

533 words

Thought I’m not likely to manage my data layer via a shell, understanding how to access my database from the shell is useful as it helps to illuminate the actions I’m taking within my application.

This post is an example of doing this for a Mongo database using the mongosh.

My current Mongo cluster is just the Sample Databases that MongoDB offers.

That means my cluster has eight databases, each with its own set of collections.

How can you replicate this same query locally?

Connect to the DB

My cluster’s name is sandbox, so when I want to connect, I can find my URI via MongoDB Atlas.

% mongosh "mongodb+srv://sandbox.tv0tb.mongodb.net/" --username admin
Current Mongosh Log ID: 61a0114fae3e07313ecc3991
Connecting to:          mongodb+srv://sandbox.tv0tb.mongodb.net/
Using MongoDB:          4.4.10
Using Mongosh:          1.1.4

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

Atlas atlas-flxc54-shard-0 [primary] test>

By default, it will place you into the test.

Show Available Databases

Now that we’re connected, we can look at the DBs that are available.

Based on the Atlas view, we expect 8 databases.

Using the Mongo shell, we can see what’s available:

Atlas atlas-flxc54-shard-0 [primary] test> show dbs
sample_airbnb       55.2 MB
sample_analytics    9.94 MB
sample_geospatial   1.79 MB
sample_mflix        50.5 MB
sample_restaurants  6.23 MB
sample_supplies     1.02 MB
sample_training     46.4 MB
sample_weatherdata  2.52 MB
admin                369 kB
local               6.44 GB

Select A DB For Use

Now that we know our available DBs, we can select them from the shell with the use command:

Atlas atlas-flxc54-shard-0 [primary] test> use sample_training
switched to db sample_training

Show Collections

Similar to show DBs, once you’re in a database, we may want to know which collections are available to us.

In our case, we’re currently looking at the sample_training database, so what collections are available?

Atlas atlas-flxc54-shard-0 [primary] sample_training> show collections
companies
grades
inspections
posts
routes
trips
zips

Searching Collections

Now that we’ve selected a database, we don’t need to specify it. This allows for an ergonomic experience in searching for a record within a DB.

We can use .find([query]):

By default, the find will return the first 20 records in the collection without any sorting.

Atlas atlas-flxc54-shard-0 [primary] test> db.zips.find()
[
  {
    _id: ObjectId("5c8eccc1caa187d17ca6ed16"),
    city: 'ALPINE',
    zip: '35014',
    loc: { y: 33.331165, x: 86.208934 },
    pop: 3062,
    state: 'AL'
  },
  {
    _id: ObjectId("5c8eccc1caa187d17ca6ed17"),
    city: 'BESSEMER',
    zip: '35020',
    loc: { y: 33.409002, x: 86.947547 },
    pop: 40549,
    state: 'AL'
  },
  {
    _id: ObjectId("5c8eccc1caa187d17ca6ed18"),
    city: 'ACMAR',
    zip: '35004',
    loc: { y: 33.584132, x: 86.51557 },
    pop: 6055,
    state: 'AL'
  },
  //...
]

Simple queries can look like:

Atlas atlas-flxc54-shard-0 [primary] sample_training> db.zips.find({"state":"MN", "city":"SAINT PAUL"})

This will return all of the records in the collection which match the criteria of the state in the record as “MN” and the city as “SAINT PAUL”.

We can get a little fancier:

db.zips.find({"state":"MN", "city":"SAINT PAUL", "pop": {$lt: 10000}})
[
  {
    _id: ObjectId("5c8eccc1caa187d17ca71f1f"),
    city: 'SAINT PAUL',
    zip: '55114',
    loc: { y: 44.967968, x: 93.198067 },
    pop: 1402,
    state: 'MN'
  }
]

Resources

For more on CRUD operations like find within MongoDB, see this page on the MongoDB site.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!