1

I just want to add a new field through $project pipeline and let the other properties to slip through for further processing, I know that you can do this :

db.people.aggregate([
     {$project: {name: 1, address: 1, birth_month: {$month: "$birthdate"}}}
])

But with more and more complex document, I have a great difficulty to write 20++ field name in $project. Can I just add a field through aggregation pipeline in such a way that I don't have to specified other field one by one, something like

db.people.aggregate([
     {$appendField: {birth_month: {$month: "$birthdate"}}}
])
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
DennyHiu
  • 4,861
  • 8
  • 48
  • 80
  • in that case dont add 20+ field rather put that field in project which you dont want {$project: {name: 0}} in that case it will select all field other than name. – Amit Shah Feb 26 '16 at 04:25
  • I think you misunderstand, I want to preserve the original document with all of its fields intact, but with an additional field (birth_month) – DennyHiu Feb 26 '16 at 04:31
  • .... and without having to write the other field names down in $project – DennyHiu Feb 26 '16 at 04:35
  • Thanks, Yes, that is exactly what I want. unfortunately the OP doesn't approved it as answer so what should I do here? answer my own question? – DennyHiu Feb 26 '16 at 07:14

1 Answers1

1

Finally, I was able to solve this problem. Just read the old post here (MongoDB $project: Retain previous pipeline fields, Thanks to @Johnny HK). Here's my solution (mongo 2.6 or later):

db.people.aggregate([
  {$project: {doc: "$$ROOT", birth_month: {$month: "$birthdate"}}}
  {$group: {_id: "$doc.gender"} } <-- here you can use fields of the original doc via $doc
])
Community
  • 1
  • 1
DennyHiu
  • 4,861
  • 8
  • 48
  • 80