How to hide one subdocument in the MongoDB aggregation pipeline?

In the request, find()you can hide the fields with the projection document in the second argument:

var cursor = collection.find(query, {
    '_id': false,
    'unwanted': false
});

It will return any fields and subdocuments in the document. It makes sense.

Why are the rules different when you put this projectiondocument in aggregation pipeline? $projectdoes not work:

var cursor = collection.aggregate([
    {
        $match      : query
    },
    {
        $project    : {
        '_id': false,
        'unwanted': false
        }
    }
]);

Problem:

exception: The top-level _id field is the only field currently supported 
for exclusion

How to hide a specific subdocument without resorting to explicit inclusions of all the fields that I want?

edit: Documents have an arbitrary number of fields without a specific scheme, except for some indexed fields. Therefore, I cannot specify what I want to include, because I do not know what additional fields will be in the document.

, _id - unwanted. .


:

, , , . :

// node.js

var cursor = collection.aggregate([
    {
        $match     : query
    },
    // ...
]);

cursor.toArray(function(array){
    for (var i = 0; i < array.length; i++) {
        var document = array[i];
        delete document._id;
        delete document.unwanted;
    }
})

, cursor array 16 . , .

, , , find() , aggregate() ? ? MongoDB, find(). , , ?

, MongoDB 2.6 $redact, , , . , MongoDB 2.4.

+4
1

, , :

+-----------------------+---------------------------------------------------------+
|                Syntax | Description                                              |
+-----------------------+---------------------------------------------------------+
|  <field>: <1 or true> | Specify the inclusion of a field.                        |
|     _id: <0 or false> | Specify the suppression of the _id field.                |
| <field>: <expression> | Add a new field or reset the value of an existing field. |
+-----------------------+---------------------------------------------------------+

, :

,

, $project , , , . :

project_doc = {}
for field in fields
    if field not in to_be_hidden_fields:
        project_doc[field] = "$" + field
return {"$project": project_doc}

,

, , $project ; .. $project .

$project .


, , , .

, : , ? , , MongoDB $project.

+2

Source: https://habr.com/ru/post/1589461/


All Articles