Skip to content

Commit b7f5998

Browse files
$project example
1 parent 08724fb commit b7f5998

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

mongodb-code.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,3 +299,59 @@ db.accounts.dropIndexes()
299299
<div align="right">
300300
<b><a href="#">↥ back to top</a></b>
301301
</div>
302+
303+
304+
305+
## Q. ***Select only selected elements from given collection?***
306+
307+
Consider a ```books``` collection with the following document:
308+
309+
```js
310+
{
311+
"_id" : 1,
312+
title: "abc123",
313+
isbn: "0001122223334",
314+
author: { last: "zzz", first: "aaa" },
315+
copies: 5
316+
}
317+
```
318+
319+
The following ```$project``` stage adds the new fields isbn, lastName, and copiesSold:
320+
321+
```js
322+
db.books.aggregate([
323+
{
324+
$project : {
325+
title:1,
326+
isbn: {
327+
prefix: { $substr: [ "$isbn", 0, 3 ] },
328+
group: { $substr: [ "$isbn", 3, 2 ] },
329+
publisher: { $substr: [ "$isbn", 5, 4 ] },
330+
title: { $substr: [ "$isbn", 9, 3 ] },
331+
checkDigit: { $substr: [ "$isbn", 12, 1] }
332+
},
333+
lastName: "$author.last",
334+
copiesSold: "$copies"
335+
}
336+
}
337+
])
338+
```
339+
The operation results in the following document:
340+
341+
```js
342+
{
343+
"_id" : 1,
344+
"title" : "abc123",
345+
"isbn" : {
346+
"prefix" : "000",
347+
"group" : "11",
348+
"publisher" : "2222",
349+
"title" : "333",
350+
"checkDigit" : "4"
351+
},
352+
"lastName" : "zzz",
353+
"copiesSold" : 5
354+
}
355+
```
356+
357+

0 commit comments

Comments
 (0)