File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -299,3 +299,59 @@ db.accounts.dropIndexes()
299
299
<div align="right">
300
300
<b><a href="#">↥ back to top</a></b>
301
301
</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
+
You can’t perform that action at this time.
0 commit comments