2013-08-27 38 views
1

選擇每一個我有一個集合與架構: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命令,它只會返回一個或兩個結果。任何建議如何我可以提供三個非唯一類型,並總是得到每種類型的三個報價?

+0

要麼你應該刪除您查詢'$ groupby'一步或者我沒有正確理解你。 – Shad

+0

@Shad然後它返回所有具有該類型的文檔,而不僅僅是其中的一個。我可以看到我的意思,我會編輯我的問題。謝謝。 – AdrianCooney

回答

0

你將需要需要編寫自己的函數:

  • 需要你類型數組作爲參數。
  • 實例化一個空的skipDocs散列/對象例如

    var objSkipDocs = {};

  • 對於您的每個元素類型數組將零值置換爲散列中該值的一個鍵。

    for(var i = 0; i < arrayTypes.length; i ++)objSkipDocs [arrayTypes [i]] = 0; }

  • 對於您的類型的每個元素數組嘗試獲取文檔例如({'type':arrayTypes [i]})。skip(objSkipDocs [arrayTypes [i]]);}}。

    objSkipDocs [arrayTypes [i]] + = 1;

  • 做一些與檢索到的文檔