2014-06-09 37 views
-1

enter image description here在操作MongoDB中

這是我收集的結構損傷包含傷害數據我有兩個injuryid,所以我想JST那些受傷 例如我有2個IDS(538d9e7ed173e5202a000065,538f21868a5fc5e01f000065),那麼我必須只得到1 ×2陣列我的用戶在運營商英國電信仍然獲得全部3個array..i嘗試下面的查詢

 db.users.find(
        {"injury._id":{$in:[ObjectId("538d9e7ed173e5202a000065"), 
             ObjectId("538f21868a5fc5e01f000065")]} 
        }) 

使用,我得到了所有3陣列

+1

是的。它是一個數組,這不會過濾數組。你也有類似的問題,你以前曾經問過,並且已經給出瞭如何做到這一點的答案,但是你沒有清楚地將你的數據展示給他們中的任何一個,並且你通過提供屏幕截圖而不是實際數據來做同樣的事情。我建議你回到以前的問題並澄清你的數據,這樣你才能真正領導如何做到這一點。 –

回答

1

你需要了解這裏的是您查詢旨在過濾「文檔」,並且不會過濾文檔內的數組「元素」。爲了實際過濾數組內容多爲單比賽越多,你需要使用聚合框架:

db.users.aggregate([ 
    // Matches the "documents" containing those elements in the array 
    { "$match": { 
     "injury._id":{ 
      "$in": [ 
       ObjectId("538d9e7ed173e5202a000065"), 
       ObjectId("538f21868a5fc5e01f000065") 
      ] 
     } 
    }}, 

    // Unwind the array to de-normalize as documents 
    { "$unwind": "$injury" }, 

    // Match the array members 
    { "$match": { 
     "injury._id":{ 
      "$in": [ 
       ObjectId("538d9e7ed173e5202a000065"), 
       ObjectId("538f21868a5fc5e01f000065") 
      ] 
     } 
    }}, 

    // Group back as an array 
    { "$group": { 
     "_id": "$_id", 
     "injury": { "$push": "$injury" } 
    }} 

]) 

在MongoDB的2.6和更大的可利用$map到濾鏡陣列:

db.users.aggregate([ 
    // Matches the "documents" containing those elements in the array 
    { "$match": { 
     "injury._id":{ 
      "$in": [ 
       ObjectId("538d9e7ed173e5202a000065"), 
       ObjectId("538f21868a5fc5e01f000065") 
      ] 
     } 
    }}, 

    // Project with $map to filter 
    { "$project": { 
     "injury": { 
      "$setDifference": [ 
       { "$map": { 
        "input": "$injury", 
        "as": "el", 
        "in": { 
         "$cond": [ 
         { 
          "$or": [ 
            { "$eq": [ 
             "$$el._id" 
             ObjectId("538d9e7ed173e5202a000065") 
            ]}, 
            { "$eq": [ 
             "$$el._id" 
             ObjectId("538f21868a5fc5e01f000065") 
            ]} 
           ] 
          }, 
          "$$el", 
          false 
         ] 
        } 
       }}, 
       [false] 
      ] 
     } 
    }} 

]) 
+0

ya謝謝...其工作 – MaTya

+0

@MaTya我相信它確實如此。通常很好地「接受」幫助你的答案。幫助人們瞭解解決方案的工作原理並幫助那些幫助你的人。別忘了你還有其他問題。 –