Mongodb group by dbref field

霸气de小男生 提交于 2019-12-24 04:27:32

问题


I need group products by model. Each product has model field - DBRef to Models collection. I tried use this aggregate query, but have error FieldPath field names may not start with '$'.

Aggregation query:

db.Products.aggregate([
    { $project: { _id: 0, model: 1, isActive: 1 } },
    { $group: { _id: "$model.$id", actives: { $push: "$isActive" } }}
]);

Example of product document:

{
    _id: ObjectId("54f48610e31701d2184dede5"),
    isActive: true,
    model: {
        $db: "database",
        $ref: "Models",
        $id: ObjectId("....")
    }
}

回答1:


There used to be a section in the manual that explicity stated that DBRef is not supported under the aggregation framework, along with various other BSON types.

The old passage read as shown in this google groups archive message:

Warning: The pipeline cannot operate on values of the following types: Binary, Symbol, MinKey, MaxKey, DBRef, Code, and CodeWScope.

It might still be there somewhere but I just cannot seem to find it right now :)

Also as aluded to in that message thread is that aside from this not being supported in the aggregation framework, then your other option ( and only real option for aggregation ) is to use the mapReduce method instead. As a shell example:

db.Products.mapReduce(
    function() {
        emit( this.model.$id, { "actives": [this.isActive] } );
    },
    function(key,values) {
        var result = { "actives": [] };
        values.forEach(function(value) {
            value.actives.forEach(function(active) {
                result.actives.push( active );
            });
        });
    },
    { "out": { "inline": 1 } }
)

It doesn't look as nice because of the arbitrary { "_id": "", "value": { } } structure of mapReduce results, but it does allow the sort of aggregation you are looking for.

There is also reference to this JIRA Issue: SERVER-14466, but I would not hold out for much movement on that front.

So you can use mapReduce but it would be advised to move away from using DBRef and define an alternate form of "manual references" either embedding "collection" and "database" information or relying on external definition of such things in your application schema, depending on your needs. As long as you follow the same rules there then you can use the aggregation framework for anything with valid property names.



来源:https://stackoverflow.com/questions/28836120/mongodb-group-by-dbref-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!