MongoDB – simple queries in the Mongoshell

MongoDB – simple queries in the Mongoshell

What is MongoDB?

MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents, allowing for easy storage and retrieval of structured, semi-structured, and unstructured data. Unlike traditional relational databases that use tables and rows, MongoDB uses collections and documents, making it more adaptable to changing data structures. It was designed to handle large volumes of data and is known for its scalability, flexibility, and ease of use. 

What is Mongoshell?

The MongoShell is an interactive command window for the MongoDB database. You can use it for the CRUD operations. The MongoShell comes with the installation of MongoDB. After test, you type in the commands.

What is CRUD?

Create, Read, Update, Delete

My installed MongoDB version

  • MongoDB: 7.0.25
  • MongoShell: 2.5.9

The requirements:

The command

mongosh

Which databases I already have?

show dbs

MongoDB show dbs (show databases)

To move into the database

use Laender

To show the collections (total)

show collections

MongoDB show collections Laender (Länder)

The command syntax

db.collection.find()

Example

The collection Espana is available in the database

db.Espana.find()

Then the MongoShell will show you the entries of this collection in the JSON format.

My example of the collection Espana

{
_id: ObjectId(‚6341881fe5ce4dc0eb1a6ea7‘),
‚Com autónoma‘: ‚País Vasco‘,
Provincia: ‚Guipúzcoa‘,
Ciudad: ‚Zarauz‘,
‚Ciudad local‘: ‚Zarauz‘,
Altitud: 4,
Superficie: 14.8,
‚Poplación‘: 23271,
Densidad: 1562.03,
‚Código postal‘: 20800
}

How many collections I have saved in „Espana“?

The old command

db.Espana.count()

The output

Laender> db.Espana.count()
DeprecationWarning: Collection.count() is deprecated. Use countDocuments or estimatedDocumentCount.
517

The new command

db.Espana.countDocuments()

The output

Laender> db.Espana.countDocuments()
517

MongoDB MongoShell db.Espana.countDocuments 517

Summary

  • open the MongoShell
  • show your installed databases
  • show your collections
  • find documents in a collection
  • count the number of documents in a collection
Die Kommentare sind geschlossen.