Skip to content

Documents and Collections πŸ—Ž

Lyes Sefiane edited this page Jan 18, 2023 · 1 revision

Table Of Contents

MongoDB Connection in Docker

lyes-s ( β—₯β—£_β—’β—€ ) ~/Documents/learning-mongo $ docker exec -it mongodb mongosh

Current Mongosh Log ID: 62a62f286a037bb3f5ea0a30
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverS
electionTimeoutMS=2000&appName=mongosh+1.5.0
Using MongoDB:          5.0.9
Using Mongosh:          1.5.0

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


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

Warning: Found ~/.mongorc.js, but not ~/.mongoshrc.js. ~/.mongorc.js will not be loaded.
  You may want to copy or rename ~/.mongorc.js to ~/.mongoshrc.js.

// Use Admin Database
test> use admin
switched to db admin

// Authentication with DB username & password
admin> db.auth("root", passwordPrompt());
Enter password
*******

// Connection Success
{ ok: 1 }

// Show Databases
admin> show dbs;
admin   100.00 KiB
config  108.00 KiB
cooker  120.00 KiB
local    72.00 KiB

// Use Cooker Database
admin> use cooker
switched to db cooker

Create Document

What is a Document ?

MongoDB documents are field-value pairs stored in a JSON like format called BSON (Binary JSON).

Using .insertOne() to Insert a Document to a Collection

Please refer to : Create One Document

Collections

What is a Collection ?

A collection is a grouping of MongoDB documents.

> show collections

recipes
users

Cursor

The Cursor is a MongoDB Collection of the document which is returned upon the find method execution. By default, it is automatically executed as a loop. However, we can explicitly get specific index document from being returned cursor. [1]

In mongosh, you can use the toArray() method to iterate the cursor and return the documents in an array.

// Access to the first element returned by the cursor
cooker> db.recipes.find({}, {"title" : 1}).toArray()[0];

{
  _id: ObjectId("5e878f5220a4f574c0aa56db"),
  title: 'Maple Smoked Salmon v2'
}

The toArray() method loads into RAM all documents returned by the cursor.

The new MongoDB Shell

Examples :

Help

cooker> db.recipes.find().help()

  Collection Cursor:

    addOption                                  Adds OP_QUERY wire protocol flags, such as the tailable flag, to change the behavior of queries. Accepts: DBQuery.Option fields tailable, slaveOk, noTimeout, awaitData, exhaust, partial.
    allowDiskUse                               Sets the 'allowDiskUse' option. If no argument is passed, the default is true.
    allowPartialResults                        Sets the 'partial' option to true.
    collation                                  Specifies the collation for the cursor returned by the db.collection.find(). To use, append to the db.collection.find().
    comment                                    Adds a comment field to the query.
    count                                      Counts the number of documents referenced by a cursor.
    hasNext                                    cursor.hasNext() returns true if the cursor returned by the db.collection.find() query can iterate further to return more documents. NOTE: if the cursor is tailable with awaitData then hasNext will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead
    hint                                       Call this method on a query to override MongoDB’s default index selection and query optimization process. Use db.collection.getIndexes() to return the list of current indexes on a collection.
    limit                                      Use the limit() method on a cursor to specify the maximum number of documents the cursor will return.
    max                                        Specifies the exclusive upper bound for a specific index in order to constrain the results of find(). max() provides a way to specify an upper bound on compound key indexes.
    maxAwaitTimeMS                             Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
    min                                        Specifies the inclusive lower bound for a specific index in order to constrain the results of find(). min() provides a way to specify lower bounds on compound key indexes.
    next                                       The next document in the cursor returned by the db.collection.find() method. NOTE: if the cursor is tailable with awaitData then hasNext will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead
    noCursorTimeout                            Instructs the server to avoid closing a cursor automatically after a period of inactivity.
    oplogReplay                                Sets oplogReplay cursor flag to true.
    readPref                                   Append readPref() to a cursor to control how the client routes the query to members of the replica set.
    returnKey                                  Modifies the cursor to return index keys rather than the documents.
    size                                       A count of the number of documents that match the db.collection.find() query after applying any cursor.skip() and cursor.limit() methods.
    tailable                                   Marks the cursor as tailable.
    maxScan                                    deprecated, non-functional
    showRecordId                               Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection.
    readConcern                                Specify a read concern for the db.collection.find() method.

Console Table

cooker> const results = db.recipes.find({}, {title: 1, prep_time: 1, _id: 1}).toArray()

cooker> console.table(results)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ (index) β”‚                 _id                  β”‚          title           β”‚ prep_time β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚ ObjectId("5e878f5220a4f574c0aa56db") β”‚ 'Maple Smoked Salmon v2' β”‚    15     β”‚
β”‚    1    β”‚ ObjectId("5e6fd805fa98021236426a24") β”‚   'Chicken Soft Tacos'   β”‚    10     β”‚
β”‚    2    β”‚ ObjectId("5e87856d07beb474c074c5ca") β”‚  'Brown Sugar Meatloaf'  β”‚    12     β”‚
β”‚    3    β”‚ ObjectId("5e877cba20a4f574c0aa56da") β”‚        'Pancakes'        β”‚    10     β”‚
β”‚    4    β”‚ ObjectId("5edf1d313260aab97ea0d589") β”‚   'Zucchini Brownies'    β”‚    12     β”‚
β”‚    5    β”‚ ObjectId("5edf1cd43260aab97ea0d588") β”‚       'Apple Pie'        β”‚    25     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Auto Complete

cooker> db.recipes.find({ cook_time: {$g} })

db.recipes.find({ cook_time: {$geoIntersects  db.recipes.find({ cook_time: {$geoWithin      db.recipes.find({ cook_time: {$gt             db.recipes.find({ cook_time: {$gte
Clone this wiki locally