Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: aggregate $project add field with static value

Tags:

mongodb

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

like image 316
redexp Avatar asked Feb 27 '13 11:02

redexp


People also ask

How do you add a field in aggregate?

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 .

How do I add a field value in MongoDB?

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).

What is difference between $Group and $project in MongoDB?

$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.

How do I create a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


1 Answers

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.

like image 51
Elad Avatar answered Sep 18 '22 15:09

Elad