gpt4 book ai didi

mongoDB - 基于返回结果数量的不同查询条件

转载 作者:搜寻专家 更新时间:2023-10-30 23:37:26 25 4
gpt4 key购买 nike

我有这样一个文档-

{
type: "One",
details: "This is one",
at: "some place, where one is relevant"
}

类似架构的其他文档可以具有相同的“类型”,但具有不同的“详细信息”、“at”等。可以有多个“类型”。

现在,我想编写一个查询来返回一定数量(上限,比如 5)匹配特定“类型”的文档(我可以使用 limit$in ) 如果结果包含的文档少于 5 个,则可以省略“类型”标准。

例如,如果我只允许“一个”和“两个”作为“类型”并且我使用 5 的限制,那么如果结果的数量小于 5(比如 2),它应该返回我那些类型为“一”和“二”的文档(即 2 个文档)和另外 3 个未查看其“类型”的文档。

我希望这是有道理的!

最佳答案

如果您不喜欢使用脚本,我可以看到的选项是使用 aggregate 并引入额外的字段 weight 例如向上移动匹配的文档然后排序权重和限制总结果:

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 }
);

关于这个例子的注释。为了简单起见,我将 $in 替换为 $or 中的几个相等项。如果您不希望在最终结果中包含权重,您可以通过在聚合管道中应用另一个投影来移除它。

测试数据库:

> 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" }

结果:

> 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 }, {$project: {type: 1, details: 1, at: 1} });
{ "_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("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("5806734ba7518db4d3d2e975"), "type" : "Three", "details" : "This is three", "at" : "some place, where one is relevant" }

关于mongoDB - 基于返回结果数量的不同查询条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40079743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com