Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include all existing fields and add new fields to document

People also ask

How do I add a field to an existing document in MongoDB?

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 .

What is the use of $project in MongoDB?

The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields. Specifies the inclusion of a field.

How do I project multiple fields in MongoDB?

Use the Projection Method to Select Single or Multiple Fields for All Documents in a MongoDB Collection. A projection can explicitly include several fields. The find() method will return all the pages that match the query in the following operation.


In 4.2+, you can use the $set aggregation pipeline operator which is nothing other than an alias to $addFieldsadded in 3.4

The $addFields stage is equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.

db.collection.aggregate([
    { "$addFields": { "custom_field": "$obj.obj_field1" } }
])

You can use $$ROOT to references the root document. Keep all fields of this document in a field and try to get it after that (depending on your client system: Java, C++, ...)

 [
    {
        $project: {
            custom_field: "$obj.obj_field1",
            document: "$$ROOT"

        }
    },
    ... //group, match, and whatever...
]

>>> There's something like "include all fields" keyword that I can use in this case or some another solution?

Unfortunaly, there is no operator to "include all fields" in aggregation operation. The only reason, why, because aggregation is mostly created to group/calculate data from collection fields (sum, avg, etc.) and return all the collection's fields is not direct purpose.


To add new fields to your document you can use $addFields

from docs

and to all the fields in your document, you can use $$ROOT

db.collection.aggregate([

{ "$addFields": { "custom_field": "$obj.obj_field1" } },
{ "$group": {
        _id : "$field1",
        data: { $push : "$$ROOT" }
    }}
])