选择每一个我有一个集合与架构:MongoDB的查询 - 非唯一阵列
{
_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 pipeline命令,它只会返回一个或两个结果。任何建议如何我可以提供三个非唯一类型,并总是得到每种类型的三个报价?
要么你应该删除您查询'$ groupby'一步或者我没有正确理解你。 – Shad
@Shad然后它返回所有具有该类型的文档,而不仅仅是其中的一个。我可以看到我的意思,我会编辑我的问题。谢谢。 – AdrianCooney