【发布时间】:2015-03-27 10:41:19
【问题描述】:
我有一个主题集合,我存储这样的主题:
{
"headline" : "Quis sint et aut non quos.",
"announce" : "Rerum suscipit omnis qui ducimus.",
"body" : "<p>Ad amet et. Sed quod porro maxime doloribus.</p>",
"published_at" : ISODate("2015-02-20T21:24:52.000Z"),
"rubrics" : [
{
"slug" : "news",
"title" : "News"
}
],
"subrubrics" : [
{
"slug" : "ratings",
"title" : "Ratings"
}
],
"lists" : [
{
"title" : "News",
"slug" : "news",
"position": 12
}
]
}
我的目标是按如下方式排序主题:
- 第一部分:所有带有
lists.slug = "A"的主题按lists.position排序 - 第二部分:先行,所有
rubrics.slug or subrubrics.slug = "A"的主题按published_at排序
预期输出:
[
/* First part */
{"lists": [ { "title": "News", "slug": "news", "position": 1 } ]},
{"lists": [ { "title": "News", "slug": "news", "position": 2 } ]},
{"lists": [ { "title": "News", "slug": "news", "position": 3 } ]},
{"lists": [ { "title": "News", "slug": "news", "position": 4 } ]},
{"lists": [ { "title": "News", "slug": "news", "position": 5 } ]},
{"lists": [ { "title": "News", "slug": "news", "position": 6 } ]},
/* Second part */
{"published_at": ISODate("2015-02-20T00:00:00.000Z"), "rubrics": [ { "title": "News Rubric", "slug": "news" } ]},
{"published_at": ISODate("2015-02-19T00:00:00.000Z"), "rubrics": [ { "title": "News Rubric", "slug": "news" } ]},
{"published_at": ISODate("2015-02-18T00:00:00.000Z"), "rubrics": [ { "title": "News Rubric", "slug": "news" } ]},
{"published_at": ISODate("2015-02-17T00:00:00.000Z"), "rubrics": [ { "title": "News Rubric", "slug": "news" } ]},
{"published_at": ISODate("2015-02-16T00:00:00.000Z"), "rubrics": [ { "title": "News Rubric", "slug": "news" } ]},
{"published_at": ISODate("2015-02-15T00:00:00.000Z"), "rubrics": [ { "title": "News Rubric", "slug": "news" } ]},
{"published_at": ISODate("2015-02-13T00:00:00.000Z"), "rubrics": [ { "title": "News Rubric", "slug": "news" } ]},
]
请注意,如果我会提前获得 rubric 或 subrubric 的 slug,我现在不会。
我对 MongoDB 聚合框架不是很有经验,我只能写这样的东西,它只做第一部分(MongoID):
projection = {
_id: 0,
lists: 1,
}
slug = 'news'
collection.aggregate(
{'$project' => projection},
{'$unwind' => '$lists'},
{'$match' => {'lists.slug' => slug}},
{'$sort' => {'lists.position' => 1}}
)
如何在一个查询中完成这两个部分?会有效吗?是否可以通过 Mongoid 做到这一点?
【问题讨论】:
-
你能在这里发布你的预期输出吗?
-
@yogesh,有问题做到了
-
lists是一个数组。您希望如何对具有两个lists.position值 1 和 12 的文档相对于另一个具有lists.position值 4 和 8 的文档进行排序?假设两个文档都有一个值lists.slug = "A"。 -
lists数组肯定不能有具有相同 slug 的对象。我使用上面写的unwind运算符对具有不同lists.position值的文档进行排序。 -
深入了解预期的输出。那将需要两个预测。虽然使用逻辑或很容易在一个查询中查询不同的条件集,但查询的输出只能有一个投影。
标签: ruby-on-rails mongodb mongoid aggregation-framework