MongoDB聚合,展开,分组(相同数组)?

时间:2018-11-06 19:05:32

标签: javascript mongodb

我有一个具有以下架构的MongoDB集合(“项目”):

L!É,ZÎyÕ?=XLë(3?UK6˜#â«o±{€ò¹õç    ÒÒ—„Àd

每个项目可以具有多个类别(类别[String])。我正在使用以下JavaScript尝试获取按展开类别数组元素分组的所有项目。

const itemSchema = new mongoose.Schema({ 
  name: {
    type: String,
    required: true
    },
  description: String,
  categories: [String]
});

mongoose.model('Item', itemSchema, 'items');

数据:

const itemsGetAllByCategory = function (req, res) { 
Item    
    .aggregate( [
            { '$unwind' : '$categories' }, 
            { '$group' : 
                { '_id': '$categories',
                    'elements': { '$push': 
                      {'name': '$name', 
                       'description': '$description' }
                    }
                }
            }
    ]) 
    .sort({'_id': 1})
    .exec((err, items) => {
        if (err) {
            res
              .status(404)
              .json(err);
        } 
        else {
            res
                .status(200)
                .json(items);
        }
    });
};

我希望结果输出为:

{
"_id" : ObjectId("5be0f88e7b1b91424006d597"),
"name" : "Item 1",
"description" : "Description of Item 1",
"categories" : "[\"Category A\", \"Category B\", \"Category C\"]"
}
{
"_id" : ObjectId("5be0f88e7b1b91424006d598"),
"name" : "Item 2",
"description" : "Description of Item 2",
"categories" : "[\"Category A\", \"Category B\"]"
}
{
"_id" : ObjectId("5be0f88e7b1b91424006d599"),
"name" : "Item 3",
"description" : "Description of Item 3",
"categories" : "[\"Category A\"]"
}

但是,这段代码给了我以下输出:

[{"_id":"Category A",
  "elements":[
   {"name":"Item 1","description":"Description of Item 1"},
   {"name":"Item 2","description":"Description of Item 2"}, 
   {"name":"Item 3","description":"Description of Item 3"}]},
 {"_id":"Category B",
  "elements":[
   {"name":"Item 1","description":"Description of Item 1"},
   {"name":"Item 2","description":"Description of Item 2"}]},
 {"_id":"Category B",
  "elements":[
   {"name":"Item 1","description":"Description of Item 1"}]}]

$ unwind调用似乎并没有给我提供我希望包含多个类别的任何内容的多个输出文档,并且分组的类别保留为数组而不是单个字符串。 unwind()或group()或两者的代码是否有问题?

1 个答案:

答案 0 :(得分:0)

事实证明问题出在数据库中

categories: "[\"Category A\", \"Category B\", \"Category C\"]"

应该是:

categories: ["Category A", "Category B", "Category C"]

左括号和右括号后的引号导致该条目存储为单个字符串而不是字符串数组。感谢Neil Lunn的建议,我提供了更多细节,这引起了我的注意。