2017-06-05 93 views
1
"first_name" : [ 

    ] 

我有類似上面的數據庫。我想要找到field first_name和last_name的type = primary。我試過這個代碼,但它得到的所有數據:在單獨的陣列中查找具有相同值的兩個字段

var fieledUsers = { 
      'first_name': 1, 
      'last_name': 1, 

      }; 
      var matching = { 
       'first_name.type' :'primary', 
       'last_name.type' :'primary' 
      } 
      var conditionUsers = {"_id": users_id}; 
      db.collection('users').aggregate([{$project:fieledUsers},{$match:matching}],function (err, resUsers) { 

我該怎麼做。在此先感謝

回答

1

通過爲兩個屬性提供值作爲查詢條件,您始終可以「匹配」包含兩個屬性的文檔。但要獲得位置匹配需要$filter與骨料:

db.collection.aggregate([ 
    { "$match": { 
    "_id": users_id, 
    "first_name.type": "primary", 
    "last_name.type": "primary" 
    }}, 
    { "$addFields": { 
    "first_name": { 
     "$arrayElemAt": [ 
     { "$filter": { 
      "input": "$first_name", 
      "as": "el", 
      "cond": { "$eq": [ "$$el.type", "primary" ] } 
     }}, 
     0 
     ] 
    }, 
    "last_name": { 
     "$arrayElemAt": [ 
     { "$filter": { 
      "input": "$last_name", 
      "as": "el", 
      "cond": { "$eq": [ "$$el.type", "primary" ] } 
     }}, 
     0 
     ] 
    } 
    }} 
]) 

可與標準的查詢中使用的positional $ operator是罰款陣列匹配「單一」的元素。但對於多個匹配,或者在這種情況下,匹配可能位於每個陣列中的「不同」位置,則需要使用$filter進行這種操作。同樣以$arrayElemAt爲例,從數組中提取單個元素。

+0

謝謝,它的工作。但它獲取所有數據在db中,我只想獲得first_name和last_name字段。我該怎麼做 – Akashii

+0

@ThanhTùng如果你只想要這些字段,然後使用['$ project'](https://docs.mongodb.com/manual/reference/operator/aggregation/project/)而不是['$ addFields '](https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/)。 –

+0

完美。非常感謝你 – Akashii

0

據根據上述描述,請嘗試MongoDB中殼執行以下查詢的MongoDB文檔

The $elemMatch operator matches documents that contain an array 
field with at least one element that matches all the specified query 
criteria. 

作爲一種解決方案。

db.collection.find({first_name:{$elemMatch:{type:'primary'}}, 
last_name:{$elemMatch:{type:'primary'}}}) 
+0

這實際上不是'$ elemMatch'的用途。而是它的用法是匹配「多個條件」上的單個元素,通常是多個屬性。由OP和我自己使用的「查詢」部分因此是正確的並且是最優的。還提到了這個問題,因此「問題」是用於投影的[位置'$'運算符](https://docs.mongodb.com/manual/reference/operator/projection/positional/)只會返回「第一個位置匹配「。因此,對於「兩個」陣列,一箇中的匹配位置可能不是另一箇中的相同位置。 –

+0

所以問題不在於匹配「文檔」,因爲該部分已經完成。問題是關於。 「匹配數組元素」。對於MongoDB需要'$ filter'來返回正確的響應。 –

相關問題