我有一个具有以下架构的集合:
{
_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 管道命令,它只会返回一两个结果。有什么建议我可以提供三种非唯一类型并始终获得每种类型的三个引号?