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 } }
])
如此高效: