Skip to content

Commit a5f16a9

Browse files
Merge pull request #65 from mongodb-developer/improvements-to-search-in-arrays
added alternative method to filtering other attributes
2 parents 61f7420 + 74d2b2b commit a5f16a9

File tree

1 file changed

+64
-5
lines changed

1 file changed

+64
-5
lines changed

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

+64-5
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,7 @@ db.books.aggregate([
131131
</div>
132132
</details>
133133

134-
## $unwind
135-
136-
This is OK, but we get all attributes, although we're only interested in the MSRP!
137-
134+
This is okay, but We get a list of documents with a whole bunch of attributes which looks like the following:
138135

139136
```js
140137
{
@@ -168,7 +165,13 @@ This is OK, but we get all attributes, although we're only interested in the MSR
168165
]
169166
}
170167
```
171-
To improve, we'll use `$unwind`:
168+
169+
What if we are only interested in the MSRP?
170+
171+
There is more than one way to filter the unncessary keys and values:
172+
173+
### 1. Using $unwind aggregation stage
174+
See the following pipeline:
172175

173176
<Tabs groupId="aggregations">
174177
<TabItem value="atlas" label="Atlas UI">
@@ -225,4 +228,60 @@ db.books.aggregate([
225228

226229
You should get one document per attribute of the original book. All fields in these returned documents should be the same, except the ones in attributes.
227230

231+
### 🦸 2. Using $arrayToObject operator
232+
233+
We can also flatten the `attributes` array into an object using the `$arrayToObject` operator and then use a `$project` stage to filter unwanted fields.
234+
Note that `$arrayToObject` is not an aggregation stage.
235+
236+
<Tabs groupId="aggregations">
237+
<TabItem value="atlas" label="Atlas UI">
238+
239+
You need to select the `books` collection.
240+
241+
```js
242+
[
243+
{
244+
$match: {
245+
'attributes.key': 'msrp',
246+
'attributes.value': 9.99
247+
}
248+
},
249+
{
250+
$addFields: {
251+
attributes: {
252+
$arrayToObject: {
253+
$map: {
254+
input: '$attributes',
255+
as: 'attr',
256+
in: {
257+
k: '$$attr.key',
258+
v: '$$attr.value'
259+
}
260+
}
261+
}
262+
}
263+
}
264+
},
265+
{
266+
$project: { title: 1, 'attributes.msrp': 1 }
267+
}
268+
]
269+
```
270+
</TabItem>
271+
272+
<TabItem value="mongodb-shell" label="MongoDB Shell">
273+
274+
```js
275+
db.books.aggregate([
276+
{ $match: {_id: "0395623650"} },
277+
{ $unwind : "$attributes" },
278+
]);
279+
```
280+
281+
</TabItem>
282+
</Tabs>
283+
284+
🦸 Run the above aggregation to observe the difference in output as compared to using `$unwind`.
285+
286+
228287

0 commit comments

Comments
 (0)