0

我的文档结构如下:

{
  "_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
}

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

4

1 回答 1

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
}

让我知道我的数据和你的数据之间是否存在一些差异。

夏皮

于 2013-02-27T00:39:49.473 回答