我从 MongoDb 和 nodejs (使用 mongoose)开始。
我有一个收藏Stories, 每个都可以有一个或多个Tags,是这样的:
{
title: "The red fox",
content: "The red fox jumps away...",
tags: [
{
tagname: "fairytale",
user: "pippo"
},
{
tagname: "funny",
user: "pluto"
},
{
tagname: "fox",
user: "paperino"
}
]
},
... other stories
现在我想做一个标签云.
这意味着查询所有标签的故事。
在关系世界(例如 MySQL)中,我会有一个 Stories 表、一个 Tags 表和一个 Stories_Tags 表(多对多)。然后我会查询标签表或类似的东西。
有办法这样做吗? (我确定是的)
如果是,这是一个好的做法吗?或者它打破了 nosql 范式?
您能为我的架构设计想象出更好的方法吗?
以下是使用聚合框架执行此操作的方法(您需要使用刚刚发布的 2.2)。
db.stories.aggregate(
[
{
"$unwind" : "$tags"
},
{
"$group" : {
"_id" : "$tags.tagname",
"total" : {
"$sum" : 1
}
}
},
{
"$sort" : {
"total" : -1
}
}
])
您的结果将如下所示:
{
"result" : [
{
"_id" : "fairytale",
"total" : 3
},
{
"_id" : "funny",
"total" : 2
},
{
"_id" : "silly",
"total" : 1
},
{
"_id" : "fox",
"total" : 1
}
],
"ok" : 1
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)