2016-10-17 31 views
1

我有这样一个文件 -的MongoDB - 返回基于结果的数量不同的查询条件

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

类似模式的其他文件可以有不同的“细节”同“型”,“在”等等。 可以有几个'类型'。

现在,我想写一个查询,以返回给我一些匹配某些'类型'(我可以使用limit$in)的文档的某个数字(上限,也就是5),这可以省略'type'条件if结果包含少于5个文件。例如,如果我只允许“一”和“两”作为“类型”,并且使用5的限制,那么如果结果的数量少于5(比如2),它应该返回给我那些具有“一”和“二”作为它们的类型(即2个文档)和另外3个文档而没有查看它们的“类型”的文档。

我希望这是有道理的!

回答

1

如果你不喜欢排序weight使用可以看我的选择是使用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。如果您不想在最终结果中包含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" }  

结果:

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

完美@麦克 - shauneu!完美的作品! 我不禁注意到,在这个例子中,我们只有两个可能的权重 - 我假设一个用于条件匹配(so,0)和不匹配(so,1),然后按重量排序。 但是我们可以有更多的权重? 我认为应该追加到$ cond数组 - 条件和额外的重量值。是这样吗? –

+0

因为我们需要在结果文档中包含匹配和不匹配的条件,所以我们需要确保从匹配文档开始,我们会引入重量并按其排序以推送匹配的文档。 –

相关问题