2016-10-17 29 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

因爲我們需要在結果文檔中包含匹配和不匹配的條件,所以我們需要確保從匹配文檔開始,我們會引入重量並按其排序以推送匹配的文檔。 –

相關問題