2017-04-14 52 views
1

我在我的「預訂」表上得到了一個looong查詢,除非我詢問代理時,它的效果很好。當在MongoDB中查找操作的展開結果時丟失記錄

我們得到了一個「用戶」表。此表包含用戶,管理員,代理等。

「預訂」總是有一個「用戶」,這樣$查找總是很順利。

「預訂」有時有一個「代理人」,但大部分時間該領域是空白「」。所以當我做$查找時,它會打破整個查詢並且不會返回任何內容。

我想做$查找,但只有「代理」字段不是空白。 或找到一種方法,如果$查找失敗,它不會中斷整個查詢。

左側是當有實際上是一個包含一個有效的users._id「代理」場 - 在這裏我們得到的結果

的「代理」字段缺失時右側是包含空值,或包含無效值。 - 在這裏它打破了整個查詢。

enter image description here

這裏是與數據的示例來嘗試,

db.getCollection('booking').aggregate([ 
    { 
     $match: { 
      property: "001", 
      checkin: {$gte: 1483596800}, 
      checkout: {$lte: 1583596800} 
     } 
    }, 
    { 
     $lookup: { 
      from: "users", 
      localField: "user", 
      foreignField: "_id",  
      as: "users"  
     } 
    }, 
    { $unwind: "$users" }, 
    { 
     $lookup: { 
      from: "users", 
      localField: "agent", 
      foreignField: "_id",  
      as: "agent"  
     } 
    }, 
    { $unwind: "$agent"} 
]) 



booking Table 
{ 
    "_id" : "AAAAA", 
    "property" : "001", 
    "user" : "U001", 
    "agent" : "A001", 
    "checkin" : 1493596800, 
    "checkout" : 1494374400, 
    "test" : "This one will always work" 
} 
{ 
    "_id" : "BBBBB", 
    "property" : "001", 
    "user" : "U001", 
    "agent" : "", 
    "checkin" : 1493596800, 
    "checkout" : 1494374400, 
    "test" : "This one has blank agent and does not work" 
} 
{ 
    "_id" : "CCCCC", 
    "property" : "001", 
    "user" : "U001", 
    "checkin" : 1493596800, 
    "checkout" : 1494374400, 
    "test" : "This one has no agent and does not work" 
} 
{ 
    "_id" : "DDDDD", 
    "property" : "001", 
    "user" : "U001", 
    "agent" : "XXXX", 
    "checkin" : 1493596800, 
    "checkout" : 1494374400, 
    "test" : "This one has invalid agent and does not work" 
} 


users Table 
{ 
    "_id" : "U001", 
    "name" : "I am USER" 
} 
{ 
    "_id" : "A001", 
    "name" : "I am AGENT" 
} 
+0

我試過這樣的東西... \t {$ cond {if:{agent $ ne「」},然後:{$ lookup code .....} - 但無法讓它工作。 – torbenrudgaard

+0

[https://docs.mongodb.com/manual/reference/operator/aggregation/cond/](閱讀本文檔,它會幫助你完成) –

+0

@ShumiGupta已經做到了 - 頁面非常糟糕,例子很糟糕。 {$ cond:[<布爾表達式>,,]}我試過了,它不起作用 - 它不會讓我把$查找放入真實情況。 – torbenrudgaard

回答

2

,就會出現問題,當你管的$lookup$unwind結果靶向其中查找所得的陣列位於所產生的場,所述查找操作的空結果將放鬆,在那裏發生數據丟失。回溯你的聚合邏輯,並添加preserveNullAndEmptyArrays選項到有罪$unwind步驟。這將停止在該步驟中的記錄丟失,從而解決您的麻煩。