Skip to content

Commit bdafee2

Browse files
committed
Added $out and some info on $unwind
1 parent 69dcf4e commit bdafee2

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

docs/40-using-arrays/2-search-inside-objects-in-arrays.mdx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,14 @@ db.books.aggregate([
5151
{$match: {"attributes.key": "msrp", "attributes.value": 9.99} },
5252
{$project: {title: 1, attributes: 1}}
5353
]);
54-
```
54+
```
55+
56+
Here we're getting a copy of each book for each object inside the `$attributes` array. This "flattens" the array and returns many copies of the same documents, one for each different attribute that we have which will be different for each of these generated docs.
57+
58+
To understand `$unwind`, run this aggregation
59+
60+
db.books.aggregate([
61+
{ $match: {_id: "0002158698"} },
62+
{ $unwind : "$genres" },
63+
{ $project: {vectorizedSynopsis: 0, attributes: 0}}
64+
]);
Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,37 @@
11
# Saving to a collection
22

3-
You can export the result of an aggregation pipeline to a different DB / Collection
3+
You can export the result of an aggregation pipeline to a different DB / Collection. To do that just add a last aggregation stage to your pipeline:
44

55
```js
66
{ $out: { db: "<output-db>", coll: "<output-collection>" } }
7-
```
7+
```
8+
9+
You can omit the `db` attribute, in which case the new collection is created in the current DB.
10+
11+
```js
12+
{ $out: "<output-collection>" }
13+
```
14+
15+
💻 Create a copy of the books with exactly 100 pages and output as a new collection named `OneHundredPagesBooks.
16+
17+
<details>
18+
<summary>Answer</summary>
19+
<div>
20+
21+
```js
22+
let oneHundredPagesBooks = {$match: {pages: 100}};
23+
let saveToNewCollection = {$out: "OneHundredPagesBooks"}
24+
25+
db.books.aggregate([
26+
oneHundredPagesBooks,
27+
saveToNewCollection
28+
]);
29+
```
30+
31+
After running this, we should see a new collection with:
32+
33+
```js
34+
show collections
35+
```
36+
</div>
37+
</details>

0 commit comments

Comments
 (0)