Skip to content

Commit 969bbc7

Browse files
author
Chris Cho
authored
DOCSP-21519: node TLDR (#309)
* DOCSP-21519: Quick Reference page
1 parent 3404ce3 commit 969bbc7

29 files changed

+735
-25
lines changed
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
// ignored first line
2+
const { MongoClient } = require("mongodb");
3+
4+
// Replace the uri string with your MongoDB deployment's connection string.
5+
const uri =
6+
"<connection URI>";
7+
8+
const client = new MongoClient(uri);
9+
10+
async function query(coll) {
11+
await console.log("findOne");
12+
const result = await coll.findOne({ title: 'Hamlet' });
13+
await console.dir(result);
14+
}
15+
16+
async function queryMany(coll) {
17+
await console.log("find");
18+
const cursor = await coll.find({ year: 2005 });
19+
await cursor.forEach(console.dir);
20+
}
21+
22+
async function insertOne(coll) {
23+
const result = await coll.insertOne({
24+
title: 'Jackie Robinson',
25+
});
26+
await console.dir(result);
27+
}
28+
async function insertMany(coll) {
29+
const result = await coll.insertMany([
30+
{ title: 'Dangal', rating: 'Not Rated' },
31+
{ title: 'The Boss Baby', rating: 'PG' }
32+
]);
33+
await console.dir(result);
34+
}
35+
36+
async function updateOne(coll) {
37+
const result = await coll.updateOne(
38+
{ title: 'Amadeus' },
39+
{ $set: { 'imdb.rating': 9.5 } }
40+
);
41+
await console.dir(result);
42+
}
43+
44+
async function updateMany(coll) {
45+
const result = await coll.updateMany(
46+
{ year: 2001 },
47+
{ $inc: { 'imdb.votes': 100 } }
48+
);
49+
50+
await console.dir(result);
51+
}
52+
53+
async function updateArrayElement(coll) {
54+
const result = await coll.updateOne(
55+
{ title: 'Cosmos' },
56+
{ $push: { genres: 'Educational' } }
57+
);
58+
await console.dir(result);
59+
60+
const findResult = await coll.findOne({title: 'Cosmos'});
61+
await console.dir(findResult);
62+
}
63+
64+
async function replaceDocument(coll) {
65+
const result = await coll.replaceOne(
66+
{ name: 'Deli Llama', address: '2 Nassau St' },
67+
{ name: 'Lord of the Wings', zipcode: 10001 },
68+
{ upsert: true}
69+
);
70+
await console.dir(result);
71+
72+
const findResult = await coll.findOne({name: 'Lord of the Wings'});
73+
await console.dir(findResult);
74+
}
75+
76+
async function deleteOne(coll) {
77+
const result = await coll.deleteOne({ title: 'Congo' });
78+
await console.dir(result);
79+
}
80+
81+
async function deleteMany(coll) {
82+
const result = await coll.deleteMany({ title: { $regex: /^Shark.*/ } });
83+
await console.dir(result);
84+
}
85+
86+
async function bulkWriteExample(coll) {
87+
const result = await coll.bulkWrite([
88+
{
89+
insertOne: {
90+
document: {
91+
title: 'A New Movie',
92+
year: 2022
93+
}
94+
}
95+
},
96+
{
97+
deleteMany: {
98+
filter: { year: { $lt: 1970 } }
99+
}
100+
}
101+
]);
102+
await console.dir(result);
103+
}
104+
105+
async function watchStart(coll) {
106+
coll.watch([ { $match: { year: { $gte: 2022 } } } ]);
107+
}
108+
109+
async function accessCursorIterative(coll) {
110+
const cursor = coll.find().limit(10);
111+
await cursor.forEach(console.dir);
112+
}
113+
114+
async function accessCursorArray(coll) {
115+
const cursor = coll.find().limit(10);
116+
const results = await cursor.toArray();
117+
console.log(results);
118+
}
119+
120+
async function createIndex(coll) {
121+
const result = await coll.createIndex({'title':1 , 'year':-1});
122+
await console.dir(result);
123+
}
124+
125+
async function countExample(coll) {
126+
const result = await coll.countDocuments({year: 2000});
127+
await console.dir(result);
128+
}
129+
130+
async function skipExample(coll) {
131+
const cursor = await coll.find({title: {$regex: /^Rocky/ }}, { skip: 2 });
132+
await console.dir(await cursor.toArray());
133+
}
134+
135+
async function sortExample(coll) {
136+
const cursor = await coll.find().limit(50).sort({ year: 1});
137+
await cursor.forEach(console.dir);
138+
}
139+
140+
async function projectExample(coll) {
141+
const cursor = coll.find().project({ _id: 0, year: 1, imdb: 1 });
142+
await cursor.forEach(console.dir);
143+
}
144+
145+
async function searchText(coll) {
146+
const result = await coll.find({$text: { $search: 'zissou' }}).limit(30).project({title: 1});
147+
await result.forEach(console.dir);
148+
}
149+
150+
async function distinct(coll) {
151+
const result = await coll.distinct('year');
152+
await console.log(result);
153+
}
154+
155+
async function run() {
156+
try {
157+
await client.connect();
158+
159+
const database = client.db("sample_mflix");
160+
const collection = database.collection("movies");
161+
162+
//await count(collection);
163+
//await query(collection);
164+
//await queryMany(collection);
165+
//await insertOne(collection);
166+
//await insertMany(collection);
167+
//await updateOne(collection);
168+
//await updateMany(collection);
169+
//await updateArrayElement(collection);
170+
//await replaceDocument(collection);
171+
//await deleteOne(collection);
172+
//await deleteMany(collection);
173+
//await bulkWriteExample(collection);
174+
//await watchStart(collection);
175+
//await accessCursorIterative(collection);
176+
//await accessCursorArray(collection);
177+
//await countExample(collection);
178+
//await skipExample(collection);
179+
//await sortExample(collection);
180+
//await projectExample(collection);
181+
//await createIndex(collection);
182+
//await searchText(collection);
183+
//await distinct(collection);
184+
185+
} finally {
186+
await client.close();
187+
}
188+
}
189+
run().catch(console.dir);

source/fundamentals/crud/read-operations/cursor.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ pulling all matching documents into a collection in process memory.
6868
fetch, the cursor is exhausted which means it ceases to respond to methods
6969
that access the results.
7070

71+
.. _node-fundamentals-cursor-foreach:
72+
7173
For Each Functional Iteration
7274
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7375

@@ -79,6 +81,8 @@ results in a functional style:
7981
:start-after: start foreach cursor example
8082
:end-before: end foreach cursor example
8183

84+
.. _node-fundamentals-cursor-array:
85+
8286
Return an Array of All Documents
8387
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8488

source/fundamentals/crud/read-operations/geo.txt

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-fundamentals-geospatial:
2+
13
===================
24
Search Geospatially
35
===================
@@ -52,9 +54,9 @@ A ``Line`` uses two coordinates: a longitude and a latitude for each end.
5254
A ``Polygon`` consists of a list of coordinates in which the first and last
5355
coordinate are the same, effectively closing the polygon. To learn more
5456
about the GeoJSON shapes you can use in MongoDB, consult the
55-
:manual:`GeoJSON manual entry </reference/geojson/>`.
57+
:manual:`GeoJSON manual entry </reference/geojson/>`.
5658

57-
To enable querying GeoJSON data, you must add the field to a ``2dsphere``
59+
To enable querying GeoJSON data, you must add the field to a ``2dsphere``
5860
index. The following snippet creates an index on the ``location.geo`` field in
5961
the ``theaters`` collection using the ``createIndex()`` method:
6062

@@ -67,9 +69,9 @@ the ``theaters`` collection using the ``createIndex()`` method:
6769
Coordinates on a 2D Plane
6870
~~~~~~~~~~~~~~~~~~~~~~~~~
6971

70-
You can also express geospatial queries using ``x`` and ``y`` coordinates in
71-
a two-dimentional Euclidian plane. Until MongoDB, this was the only format
72-
compatible with geospatial queries, and are now referred to as
72+
You can also express geospatial queries using ``x`` and ``y`` coordinates in
73+
a two-dimentional Euclidian plane. Until MongoDB, this was the only format
74+
compatible with geospatial queries, and are now referred to as
7375
"legacy coordinate pairs".
7476

7577
Legacy coordinate pairs use the following structure:
@@ -78,8 +80,8 @@ Legacy coordinate pairs use the following structure:
7880

7981
<field> : [ x, y ]
8082

81-
The field should contain an array of two values in which the first represents
82-
the ``x`` axis value and the second represents the ``y`` axis value.
83+
The field should contain an array of two values in which the first represents
84+
the ``x`` axis value and the second represents the ``y`` axis value.
8385

8486
To enable querying using legacy coordinate pairs, create a ``2d`` index on
8587
the field on the collection. The following snippet creates an index on the
@@ -90,7 +92,7 @@ the field on the collection. The following snippet creates an index on the
9092

9193
db.shipwrecks({coordinates: "2d"})
9294

93-
See the
95+
See the
9496
:manual:`MongoDB server manual page on legacy coordinate pairs </geospatial-queries/#legacy-coordinate-pairs>`
9597
for more information.
9698

source/fundamentals/crud/read-operations/limit.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-fundamentals-limit:
2+
13
====================================
24
Limit the Number of Returned Results
35
====================================

source/fundamentals/crud/read-operations/project.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-fundamentals-project:
2+
13
==============================
24
Specify Which Fields to Return
35
==============================

source/fundamentals/crud/read-operations/retrieve.txt

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-fundamentals-retrieve-data:
2+
13
=============
24
Retrieve Data
35
=============
@@ -18,7 +20,7 @@ Overview
1820
You can use read operations to retrieve data from your MongoDB database.
1921
There are multiple types of read operations that access the data in
2022
different ways. If you want to request results based on a set of criteria
21-
from the existing set of data, you can use a find operation such as the
23+
from the existing set of data, you can use a find operation such as the
2224
``find()`` or ``findOne()`` methods.
2325

2426
You can also further specify the information you are requesting by
@@ -29,12 +31,12 @@ including additional parameters or by chaining other methods such as:
2931
- :doc:`Limit the Number of Returned Results </fundamentals/crud/read-operations/limit>`
3032
- :doc:`Specify Which Fields to Return </fundamentals/crud/read-operations/project>`
3133

32-
You can also use an aggregation operation to retrieve data. This type of
33-
operation allows you to apply an ordered pipeline of transformations to the
34+
You can also use an aggregation operation to retrieve data. This type of
35+
operation allows you to apply an ordered pipeline of transformations to the
3436
matched data.
3537

3638
If you want to monitor the database for incoming data that matches a set of
37-
criteria, you can use the watch operation to be notified in real-time when
39+
criteria, you can use the watch operation to be notified in real-time when
3840
matching data is inserted.
3941

4042
.. include:: /includes/access-cursor-note.rst
@@ -70,12 +72,12 @@ matching document or ``null`` if there are no matches.
7072
:end-before: end find crud example
7173

7274

73-
Once the operation returns, the ``findResult`` variable references a
75+
Once the operation returns, the ``findResult`` variable references a
7476
``Cursor``. You can print the documents retrieved using the ``forEach()``
7577
method as shown below:
7678

7779
.. code-block:: javascript
78-
80+
7981
await cursor.forEach(console.dir);
8082

8183

@@ -114,12 +116,12 @@ group, and arrange the result data from a collection.
114116
:end-before: end aggregate crud example
115117

116118

117-
Once the operation returns, the ``aggregateResult`` variable references a
119+
Once the operation returns, the ``aggregateResult`` variable references a
118120
``Cursor``. You can print the documents retrieved using the ``forEach()``
119121
method as shown below:
120122

121123
.. code-block:: javascript
122-
124+
123125
await cursor.forEach(console.dir);
124126

125127

@@ -137,6 +139,8 @@ group, and arrange the result data from a collection.
137139
See the MongoDB server manual pages on :manual:`aggregation </aggregation>`
138140
for more information on how to construct an aggregation pipeline.
139141

142+
.. _node-fundamentals-watch:
143+
140144
Watch / Subscribe
141145
-----------------
142146

source/fundamentals/crud/read-operations/skip.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-fundamentals-skip:
2+
13
=====================
24
Skip Returned Results
35
=====================

source/fundamentals/crud/read-operations/sort.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-fundamentals-sort:
2+
13
============
24
Sort Results
35
============

source/fundamentals/crud/read-operations/text.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
.. _node-fundamentals-text:
2+
13
===========
24
Search Text
35
===========
@@ -26,7 +28,7 @@ a **text index** on your collection. See the examples below for sample
2628
code for creating a text index and using the ``$text`` query operator.
2729

2830
.. include:: /includes/atlas-search.rst
29-
31+
3032
Examples
3133
--------
3234

0 commit comments

Comments
 (0)