Skip to content

Commit 35d33b3

Browse files
(DOCSP-18950): Improvements to writing scripts docs (#153)
* (DOCSP-18950): Improvements to writing scripts docs * Apply suggestions from code review Co-authored-by: Anna Henningsen <[email protected]> * Small edit Co-authored-by: Anna Henningsen <[email protected]>
1 parent 882d008 commit 35d33b3

File tree

3 files changed

+291
-118
lines changed

3 files changed

+291
-118
lines changed

snooty.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title = "MongoDB Shell"
33

44
intersphinx = ["https://docs.mongodb.com/manual/objects.inv"]
55

6-
toc_landing_pages = ["/run-commands", "/crud", "/field-level-encryption"]
6+
toc_landing_pages = ["/run-commands", "/crud", "/field-level-encryption", "/write-scripts"]
77

88
[constants]
99

source/require-external-modules.txt

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
=============================================
2+
Include External Files and Modules in Scripts
3+
=============================================
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. important::
14+
15+
A complete description of Node.js, modules, and the
16+
`require() <https://nodejs.org/api/modules.html#modules_require_id>`__
17+
function is out of scope for this tutorial. To learn more, see
18+
the `Node.js Documentation <https://nodejs.org/api/modules.html>`__.
19+
20+
To use files and modules in your ``mongosh`` interactions, use the
21+
`require() <https://nodejs.org/api/modules.html#modules_require_id>`__
22+
function.
23+
24+
In your ``mongosh`` scripts, you can require:
25+
26+
- Local files
27+
- Built-in Node.js modules
28+
- External (npm) Node.js modules
29+
30+
Require a Local File
31+
--------------------
32+
33+
You can use JavaScript files in ``mongosh`` scripts without any
34+
additional setup or configuration.
35+
36+
.. note::
37+
38+
``mongosh`` does not execute files imported with ``require()``.
39+
Instead, ``mongosh`` adds everything from an imported file to the
40+
current execution scope.
41+
42+
.. example::
43+
44+
To include a file named ``test.js`` that is located in the current
45+
working directory, use one of the following commands:
46+
47+
.. code-block:: javascript
48+
49+
require('./tests.js')
50+
51+
.. code-block:: javascript
52+
53+
var tests = require('./tests.js')
54+
55+
Require a Built-In Module
56+
-------------------------
57+
58+
You can require built-in Node.js modules (such as
59+
`fs <https://nodejs.org/api/fs.html#fs_file_system>`__) in ``mongosh``
60+
without any additional setup or configuration.
61+
62+
.. example::
63+
64+
The following example creates and executes a script that:
65+
66+
- Connects to a local deployment running on the default port.
67+
- Populates the ``myDatabase.employees`` collection with sample data.
68+
- Uses the ``fs`` module to write a document from the
69+
``myDatabase.employees`` collection to a file named
70+
``employee.json``.
71+
72+
1. Create a file named ``employee-to-text-file.js`` with the
73+
following contents:
74+
75+
.. code-block:: javascript
76+
77+
const fs = require('fs');
78+
79+
db = connect('mongodb://localhost/myDatabase');
80+
81+
db.employees.insertMany( [
82+
{ "name": "Alice", "department": "engineering" },
83+
{ "name": "Bob", "department": "sales" },
84+
{ "name": "Carol", "department": "finance" }
85+
] )
86+
87+
const document = db.employees.findOne();
88+
89+
fs.writeFileSync('employee.json', JSON.stringify(document));
90+
91+
#. To load and execute the ``employee-to-text-file.js`` file, run the
92+
following command from ``mongosh``:
93+
94+
.. code-block:: javascript
95+
96+
load("employee-to-text-file.js")
97+
98+
#. To confirm that the data was written to the file, open the
99+
``employee.json`` file.
100+
101+
Require an npm Module
102+
---------------------
103+
104+
You can require Node.js modules (such as those downloaded from
105+
`npm <https://www.npmjs.com/>`__). To use external modules, you must
106+
install the modules either:
107+
108+
- Globally
109+
- In the ``node_modules`` directory in your current working directory.
110+
111+
.. example::
112+
113+
.. important::
114+
115+
To run this example, you must install the `date-fns
116+
<https://www.npmjs.com/package/date-fns>`__ module either
117+
globally or in the ``node_modules`` directory in your
118+
current working directory.
119+
120+
The following example creates and executes a script that:
121+
122+
- Connects to a local deployment running on the default port.
123+
- Populates the ``myDatabase.cakeSales`` collection with sample data.
124+
- Uses the `date-fns <https://www.npmjs.com/package/date-fns>`__
125+
module to format dates.
126+
127+
1. Create a file named ``date-fns-formatting.js`` with the following
128+
contents:
129+
130+
.. code-block:: javascript
131+
132+
const formatDistance = require('date-fns/formatDistance')
133+
134+
db = connect('mongodb://localhost/myDatabase');
135+
136+
db.cakeSales.insertMany( [
137+
{ _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),
138+
state: "CA", price: 13, quantity: 120 },
139+
{ _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),
140+
state: "WA", price: 14, quantity: 140 },
141+
{ _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),
142+
state: "CA", price: 12, quantity: 145 },
143+
{ _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),
144+
state: "WA", price: 13, quantity: 104 },
145+
{ _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),
146+
state: "CA", price: 41, quantity: 162 },
147+
{ _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),
148+
state: "WA", price: 43, quantity: 134 }
149+
] )
150+
151+
const saleDate0 = db.cakeSales.findOne( { _id: 0 } ).orderDate
152+
const saleDate1 = db.cakeSales.findOne( { _id: 1 } ).orderDate
153+
154+
const saleDateDistance0 = formatDistance(saleDate0, new Date(), { addSuffix: true })
155+
const saleDateDistance1 = formatDistance(saleDate1, new Date(), { addSuffix: true })
156+
157+
print("{ _id: 0 } orderDate was " + saleDateDistance0)
158+
print("{ _id: 1 } orderDate was " + saleDateDistance1)
159+
160+
#. To load and execute the ``date-fns-formatting.js`` file, run the
161+
following command from ``mongosh``:
162+
163+
.. code-block:: javascript
164+
165+
load("date-fns-formatting.js")
166+
167+
``mongosh`` outputs something like the following:
168+
169+
.. code-block:: none
170+
:copyable: false
171+
172+
{ _id: 0 } orderDate was over 1 year ago
173+
{ _id: 1 } orderDate was 7 months ago
174+
175+
Your output may vary depending on the date that you run the example.

0 commit comments

Comments
 (0)