0

Is there any way not to write all the fields one by one in $projectstage.

I mean assume I have database structure as;

name: "",
surname: "",
age: "",
location: "",
_id: "",

bla bla bla

in project stage assume I just want to split the location field, the rest of the document is same and should be projected.

db.collection.aggregate([{$project: {"location" : {$split: ["$location" , 0]} }}])

the field list is long, and I update the query as;

db.collection.aggregate([{$project: {name: 1, surname:1, age: 1(and so on)"location" : {$split: ["$location" , 0]} }}])

Is there any short way?

mmu36478
  • 1,295
  • 4
  • 19
  • 40
  • 1
    Use [$addFields](https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/). Something like `{$addFields:{"location" : {$split: ["$location" , 0]}}}` instead of `$project` – s7vr May 04 '17 at 12:39
  • @Veeram thank you very much. you made my day. – mmu36478 May 04 '17 at 12:44
  • @Veeram I have a question but while projecting I want to remove `_id` field. with $addFields it seems not possible. How can I solve it? – mmu36478 May 04 '17 at 12:53
  • You are welcome. Use `{$project:{_id:0}}` after `$addFields` stage. More here https://docs.mongodb.com/manual/reference/operator/aggregation/project/#exclude-fields – s7vr May 04 '17 at 13:04

0 Answers0