Skip to content

Commit ac67fd2

Browse files
authored
Merge pull request #5 from mongodb-developer/agg-pipeline-array-match-update
update array match update
2 parents be071e8 + 953f4cd commit ac67fd2

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

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

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,7 @@ attributes: [
3131
],
3232
```
3333

34-
How do we search for all the books that have an msrp of 9.99? We want books that, inside `attributes` has an object with key `msrp` and value `9.99`. We can think this works:
35-
36-
```js
37-
let nineNinetyNine = {$match: {"attributes.key": "msrp", "attributes.value": 9.99}};
38-
let showOnlyTheseFields = {$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1, "attributes": 1}};
39-
40-
db.books.aggregate([
41-
nineNinetyNine,
42-
showOnlyTheseFields,
43-
]);
44-
```
45-
46-
But it doesn't. This one works:
34+
How do we search for all the books that have an msrp of 9.99? We want books that, inside `attributes` has an object with key `msrp` and value `9.99`. We can get it to work with this:
4735

4836
```js
4937
db.books.aggregate([
@@ -63,5 +51,18 @@ db.books.aggregate([
6351
{ $unwind : "$attributes" },
6452
]);
6553
```
54+
You should get one document per attribute of the original book.
55+
56+
But you can actually match documents in an array in a more straightforward fashion:
57+
58+
```js
59+
let nineNinetyNine = {$match: {"attributes.key": "msrp", "attributes.value": 9.99}};
60+
let showOnlyTheseFields = {$project: {_id: 0, title: 1, year: 1, totalInventory: 1, available: 1, "attributes": 1}};
61+
62+
db.books.aggregate([
63+
nineNinetyNine,
64+
showOnlyTheseFields,
65+
]);
66+
```
67+
6668

67-
You should get one document per attribute of the original book.

0 commit comments

Comments
 (0)