Can I somehow add custom field with static (not computed) value?
I want to prepare objects before send and I need to remove some fields with internal information and add field with some entity ID.
For example I have collection "test" with objects like this
{_id: ObjectId(...), data: {...}}
And I need to convert it to
{data: {...}, entity_id: 54}
So how can I add entity_id: 54 without looping over result in my code?
db.test.aggregate({ $project: {_id: 0, data: 1, entity_id: ? } })
Thanks
You can include one or more $addFields stages in an aggregation operation. To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
MongoDB add fieldRight-click on any cell while in Table View or Tree View. Go to Field > Add Field/Value. Choose the right field type (e.g. String). Define the field value (e.g. green).
$group is used to group input documents by the specified _id expression and for each distinct grouping, outputs a document. $project is used to pass along the documents with the requested fields to the next stage in the pipeline.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
Note that $literal was implemented in Mongo 2.6. So now you can simply write:
db.test.aggregate( {$project: {_id: 0, data: 1, entity_id: {$literal: 54}}})
See $literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With