MongoDB按数组内部元素分组

MongoDB按数组内部元素分组,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有一个文章列表,每个文章都有一个数组属性,其中列出了文章中提到的各种个人: _id: { $oid: "52b632a9e4f2ba13c82ccd23" }, providerName: "The Guardian", url: "http://feeds.theguardian.com/c/34708/f/663860/s/3516cebc/sc/38/l/0L0Stheguardian0N0Cmusic0C20A130Cdec0C220Cwaterboys0Efishermans

我有一个文章列表,每个文章都有一个数组属性,其中列出了文章中提到的各种个人:

_id: {
    $oid: "52b632a9e4f2ba13c82ccd23"
},
providerName: "The Guardian",
url: "http://feeds.theguardian.com/c/34708/f/663860/s/3516cebc/sc/38/l/0L0Stheguardian0N0Cmusic0C20A130Cdec0C220Cwaterboys0Efishermans0Eblues0Etour0Ehammersmith/story01.htm",
subject: "The Waterboys – review",
class_artist: [
    "paul mccartney"
]
我一直在尝试(未成功)根据过去7天内他们被标记的文章数量,获取所有个人艺术家(
class\u artist
)的列表

我已经做到了:

var date = new Date();
date.setDate(date.getDate() - 7);

db.articles.group({
    key: { class_artist: 1 },
    cond: { class_date: { $gt: date } },
    reduce: function ( curr, result ) { result.cnt++; },
    initial: { cnt : 0 }
}).sort({cnt: -1});
但不幸的是,它不是根据单个数组值,而是根据数组组成(即艺术家列表)来计算它们


我尝试过使用
$unwind
功能,但未能使其正常工作。

您使用的是什么框架?这不是MongoDB外壳,看起来像是一些奇怪的包装。在这种情况下,将不可用,并且您需要为中的用户使用它。以下是您想要的mongo shell:

db.articles.aggregate([
  {$match: { class_date: { $gte: date } } },
  {$project: { _id: 0, class_artist: 1 } },
  {$unwind: "$class_artist" },
  {$group: { _id: "$class_artist", tags: { $sum: 1 } }},
  {$project: { _id: 0,class_artist: "$_id", tags: 1 } },
  {$sort: { tags: -1 } }
])
如此高效:

  • 按日期,因为您已经为过去7天设置了var
  • 只有我们需要的字段{我们只需要一个!}
  • 数组,因此现在每个文档中的每个数组元素都有一个记录
  • 从扩展文档看艺术家
  • 将项目转换为文档格式,您可以将其用作组,并使用_id
  • 以相反的顺序显示结果,以便首先看到标记的顶部
  • 聚合的好处是,你可以逐步建立这些阶段,看看发生了什么

    根据需要摇动并烘焙到您自己的驱动程序实现或ODM框架中。

    FYI,“怪异包装器”格式是在JavaScript中实现的,早于聚合框架。另见:。