4

我知道有很多话题在谈论这个问题,但我无法弄清楚我的实现中出了什么问题。

我有以下文件:

{
  "_id" : ObjectId("510a353929e16756d5000009"),
  "skills" : [
    [
      "UserEmbed::Author::Skills::Copywriting",
      "UserEmbed::Author::Skills::Proofreading",
      "UserEmbed::Author::Skills::Proofreading",
      "UserEmbed::Author::Skills::Translation",
      "UserEmbed::Author::Skills::Translation",
      "UserEmbed::Author::Skills::Translation"
    ]
  ]
}

我想要这样的东西:

{
  "UserEmbed::Author::Skills::Copywriting": 1,    
  "UserEmbed::Author::Skills::Proofreading": 2,
  "UserEmbed::Author::Skills::Translation": 3
}

这是我所拥有的(首先$group是从我的原始文档结构中获取上面的文档):

aggregate([ { $group: { _id: "$_id", skills: { $addToSet : "$author_profile.skills._type" } } }, { $unwind : "$skills" }, { $group : { _id : "$skills", count: { $sum : 1 } } }])

它返回类似这样的内容(与其他文件):

{
  "_id" : [
    "UserEmbed::Author::Skills::Copywriting",
    "UserEmbed::Author::Skills::Copywriting",
    "UserEmbed::Author::Skills::Copywriting",
    "UserEmbed::Author::Skills::Translation",
    "UserEmbed::Author::Skills::Translation",
    "UserEmbed::Author::Skills::Translation"
  ],
  "count" : 1
}

似乎$group无法正常工作。我是不是误会了什么?

4

1 回答 1

6

鉴于您的文档包含数组数组,您需要引入第二个$unwindfor $skills

db.so.aggregate([
    { $group: { _id: "$_id", 
        skills: { $addToSet : "$author_profile.skills._type" }}},
    { $unwind : "$skills" }, 
    { $unwind: "$skills" },
    { $group : { _id : "$skills", count: { $sum : 1 } } }])

产生:

"result" : [
        {
            "_id" : "UserEmbed::Author::Skills::Translation",
            "count" : 3
        },
        {
            "_id" : "UserEmbed::Author::Skills::Proofreading",
            "count" : 2
        },
        {
            "_id" : "UserEmbed::Author::Skills::Copywriting",
            "count" : 1
        }
    ],
"ok" : 1
于 2013-07-09T12:43:54.867 回答