← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 4 of 7

$project का उपयोग

$project हर document में fields choose, rename, और compute करता है।

In this page:

  1. $project
Syntax
javascript
{ $project: { field1: 1, field2: 1, _id: 0, computed: { $multiply: ["$a", "$b"] } } }

$project

1 से fields include करें, 0 से exclude करें, और $concat, $multiply, और $cond जैसे expressions से नई fields compute करें। यह अगले stage या final output के लिए documents reshape करता है। $addFields और $set बाकी रखते हुए computed fields add करते हैं।

Note: $addFields existing fields रखता है; $project shape replace करता है।

उदाहरण: $project

bash
test> db.people.insertMany([{ _id: 1, first: "Ada", last: "Lovelace", born: 1815 }, { _id: 2, first: "Alan", last: "Turing", born: 1912 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.people.aggregate([{ $project: { _id: 0, fullName: { $concat: ["$first", " ", "$last"] } } }])
[ { fullName: 'Ada Lovelace' }, { fullName: 'Alan Turing' } ]
test> db.people.aggregate([{ $project: { _id: 0, born: 1, century: { $ceil: { $divide: ["$born", 100] } } } }])
[ { born: 1815, century: 19 }, { born: 1912, century: 20 } ]
test> db.people.aggregate([{ $addFields: { initials: { $concat: [{ $substr: ["$first", 0, 1] }, { $substr: ["$last", 0, 1] }] } } }, { $project: { _id: 0, initials: 1, born: 1 } }])
[ { born: 1815, initials: 'AL' }, { born: 1912, initials: 'AT' } ]

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि _id default से included है
  2. Include और exclude mix करना
  3. जब $addFields simpler हो $project इस्तेमाल करना
चैप्टर सारांश
  • $project documents reshape करता है
  • 1 include करता है और 0 exclude करता है
  • Expressions नई fields compute करते हैं
  • $addFields बाकी रखता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.