2017-06-05 42 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'来返回正确的响应。 –

相关问题