如何计算mongo中的数组元素

时间:2013-07-09 10:21:32

标签: mongodb

我知道有很多话题在讨论那些但我无法弄清楚我的实施中出了什么问题。

我有以下文件:

{
  "_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无法正常工作。我误解了什么吗?

1 个答案:

答案 0 :(得分:6)

鉴于您的文档包含一系列数组,您需要为$unwind引入第二个$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