我有这样的文件 -
{
type: "One",
details: "This is one",
at: "some place, where one is relevant"
}
类似架构的其他文档可以具有相同的'类型'有不同的详细信息',' at'等。 可以有几种类型的
。现在,我想写一个查询来返回一定数量(上限,比方说5)符合某些'类型的文件(我可以使用limit
和{ {1}})可以省略'类型'如果结果包含少于5个文档的标准。
例如,如果我只允许“一个人”。和'两个'作为'键入'并且我使用5的限制,然后如果结果的数量小于5(比如2),它应该返回那些具有' One'和'两个'作为他们的类型(即2个文件)和3个以上的文件而不查看他们的'类型'。
我希望这是有道理的!
答案 0 :(得分:1)
如果您不想使用脚本我可以看到的选项是使用aggregate
引入额外的字段weight
,例如提升匹配的文档,然后按{{1}排序并限制总结果:
weight
关于此示例的说明。为了简单起见,我将$ in替换为$ equals。如果您不想在最终结果中使用db.test.aggregate({
$project: {
type: 1,
details: 1,
at: 1,
weight: {
$cond: [
{ "$or": [
{$eq: ["$type", "One"] },
{$eq: ["$type", "Two"] }
] },
0, 1] }
} },
{$sort: {weight: 1}},
{ $limit : 5 }
);
,则可以通过在汇总管道中应用其他投影来删除它。
测试数据库:
weight
结果:
> db.test.find({})
{ "_id" : ObjectId("58067329a7518db4d3d2e973"), "type" : "One", "details" : "This is one", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806733da7518db4d3d2e974"), "type" : "Two", "details" : "This is two", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806734ba7518db4d3d2e975"), "type" : "Three", "details" : "This is three", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("58067374a7518db4d3d2e976"), "type" : "Four", "details" : "This is four", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("58067381a7518db4d3d2e977"), "type" : "Five", "details" : "This is five", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("5806738fa7518db4d3d2e978"), "type" : "Six", "details" : "This is six", "at" : "some place, where one is relevant" }
{ "_id" : ObjectId("580673cfa7518db4d3d2e979"), "type" : "Seven", "details" : "This is seven", "at" : "some place, where one is relevant" }