【发布时间】:2013-08-30 12:14:36
【问题描述】:
我有一个具有以下架构的集合:
{
_id: 521cc63c19752c562300001a,
author: 'John',
quote: 'A quote',
type: 1,
stars:
[{ _id: 521cc63c19752c562300001b,
user: 521cc63c19752c5623000003,
date: Tue Aug 27 2013 16:31:08 GMT+0100 (IST) }]
}
我正在尝试选择在特定数组中具有类型的文档。例如,如果类型是唯一的,它会返回每个类型的三个引号,完全符合预期:
db.quotes.aggregate([
{$match: {
"type": {
$in: [1, 2, 3] //The unique types
}
}},
// Group by the type
{$group: {
_id: "$type",
id: { $first: "$_id" },
author: { $first: "$author" },
stars: { $first: "$stars" },
description: { $first: "$description" }
}},
// Map/project the first result of each group
// to their respective keys
{$project: {
_id: "$id",
type: "$_id",
author: "$author",
description: "$description"
stars: "$stars"
}}
]);
我的问题是类型可能并不总是唯一的。我可能必须找到三个具有相同类型的文档([1, 1, 1])或两个相同且一个唯一的文档([1, 2, 2])。当出现这种情况时,由于 $group by type 管道命令,它只会返回一两个结果。有什么建议我可以提供三种非唯一类型并始终得到每种类型的三个引号?
【问题讨论】:
-
要么你应该从你的查询中删除
$groupby步骤,要么我没有正确理解你。 -
@Shad 然后它返回所有具有该类型的文档,而不仅仅是每个文档。我可以看到我是如何暗示的,我将编辑我的问题。谢谢。
标签: mongodb mongoose aggregation-framework nosql