@@ -14,12 +14,78 @@ Run Commands in ``mongosh``
14
14
15
15
.. include:: /includes/admonitions/fact-mdb-shell-beta.rst
16
16
17
- For documentation of basic MongoDB operations in ``mongosh``, see:
17
+ To run commands in ``mongosh``, you must first
18
+ :ref:`connect to a MongoDB deployment <mdb-shell-connect>`.
18
19
19
- - :doc:`/crud`
20
+ Switch Databases
21
+ ----------------
20
22
21
- - :doc:`/run-agg-pipelines`
23
+ To display the database you are using, type ``db``:
22
24
25
+ .. code-block:: sh
26
+
27
+ db
28
+
29
+ The operation should return ``test``, which is the default database.
30
+
31
+ To switch databases, issue the ``use <db>`` helper, as in the
32
+ following example:
33
+
34
+ .. code-block:: javascript
35
+
36
+ use <database>
37
+
38
+ To access a different database from the current database without
39
+ switching your current database context, see the
40
+ :method:`db.getSiblingDB()` method.
41
+
42
+ To list the databases available to the user, use the helper ``show
43
+ dbs``.
44
+
45
+ Create a New Database and Collection
46
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47
+
48
+ To create a new database, issue the ``use <db>`` command with the
49
+ database that you would like to create. For example, the following
50
+ commands create both the database ``myNewDatabase`` and the
51
+ :term:`collection` ``myCollection`` using the
52
+ :method:`~db.collection.insertOne()` operation:
53
+
54
+ .. code-block:: javascript
55
+
56
+ use myNewDatabase
57
+ db.myCollection.insertOne( { x: 1 } );
58
+
59
+ If a collection does not exist, MongoDB creates the collection when you
60
+ first store data for that collection.
61
+
62
+ Insert Data into a Collection
63
+ -----------------------------
64
+
65
+ The :method:`db.myCollection.insertOne() <db.collection.insertOne()>` is one
66
+ of the :doc:`methods available in mongosh </reference/methods>`.
67
+
68
+ - ``db`` refers to the current database.
69
+
70
+ - ``myCollection`` is the name of the collection.
71
+
72
+ If ``mongosh`` does not accept the name of a collection,
73
+ you can use the alternative :method:`db.getCollection()` syntax.
74
+ For instance, if a collection name contains a space or hyphen, starts
75
+ with a number, or conflicts with a built-in function:
76
+
77
+ .. code-block:: javascript
78
+
79
+ db.getCollection("3 test").find()
80
+ db.getCollection("3-test").find()
81
+ db.getCollection("stats").find()
82
+
83
+ For more documentation of basic MongoDB operations in ``mongosh``, see:
84
+
85
+ - :doc:`/crud/insert`
86
+ - :doc:`/crud/read`
87
+ - :doc:`/crud/update`
88
+ - :doc:`/crud/delete`
23
89
- :doc:`/reference/methods`
24
90
25
91
Terminate a Running Command
0 commit comments