MongoDB Aggregation Framework:使用$group时出现$unroll错误



我有一个如下的文档结构:

{
  "_id" : NumberLong("80000000012"),
[...]
  "categories" : [{
      "parent" : "MANUFACTURER",
      "category" : "Chevrolet"
    }, {
      "parent" : "MISCELLANEOUS",
      "category" : "Miscellaneous"
    }],
[...]
}

我正在尝试为每个"父"字段获取一个不同的所有"类别"字段列表。我试图利用聚合框架来完成以下查询:

db.posts_temp.aggregate(
    {$unwind : '$categories'},
    {$match : {'categories.parent' : 'MISCELLANEOUS'}},
    {$project : {
        '_id' : 0,
        parent : '$categories.parent',
        category : '$categories.category'
        }
    },
    {
        $group : { 
            _id : '$parent',
            category : {$addToSet : '$category'}
        }
    }
);

运行此查询返回以下错误:

{
    "errmsg" : "exception: $unwind:  value at end of field path must be an array",
    "code" : 15978,
    "ok" : 0
}

这似乎与查询的组部分有关,因为当我删除它时,查询会正确运行,但很明显,数据不是我想要的位置。

我刚刚尝试在我的mongo实例上执行上面的聚合查询。下面是我的3个文档,每个文档都有一个由两个嵌套文档组成的类别键。

这是我的数据:

{
    "_id" : ObjectId("512d5252b748191fefbd4698"),
    "categories" : [
        {
            "parent" : "MANUFACTURER",
            "category" : "Chevrolet"
        },
        {
            "parent" : "MISCELLANEOUS",
            "category" : "Miscellaneous"
        }
    ]
}
{
    "_id" : ObjectId("512d535cb748191fefbd4699"),
    "categories" : [
        {
            "parent" : "MANUFACTURER",
            "category" : "Chevrolet"
        },
        {
            "parent" : "MISCELLANEOUS",
            "category" : "Pickup"
        }
    ]
}
{
    "_id" : ObjectId("512d536eb748191fefbd469a"),
    "categories" : [
        {
            "parent" : "MANUFACTURER",
            "category" : "Toyota"
        },
        {
            "parent" : "MISCELLANEOUS",
            "category" : "Miscellaneous"
        }
    ]
}

这是我运行的您的聚合查询:

db.posts_temp.aggregate( {$unwind:'$categories'} , {$match: {'categories.parent':'MISCELLANEOUS'}}, {$project:{'_id':0, parent: '$categories.parent', category:'$categories.category'}}, {$group:{_id:'$parent', category:{$addToSet:'$category'}}})

结果如下:

{
    "result" : [
        {
            "_id" : "MISCELLANEOUS",
            "category" : [
                "Pickup",
                "Miscellaneous"
            ]
        }
    ],
    "ok" : 1
}

如果我的数据和你的数据有出入,请告诉我。

CSharpie

相关内容

  • 没有找到相关文章

最新更新