Akashii
Akashii

Reputation: 2281

Find two fields with the same value within separate arrays

"first_name" : [ 

    ]

I have database like above . I want find field first_name and last_name have type = primary . I tried this code but it get all data :

 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) {

How can I do it . Thank in advance

Upvotes: 1

Views: 672

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

According to MongoDB documentation

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

As a solution according to above mentioned description please try executing following query in MongoDB shell.

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

Upvotes: 0

Neil Lunn
Neil Lunn

Reputation: 151220

You can always "match" the document that contains both properties by supplying the values to both properties as the query condition. But to get the positional match to both you need $filter with aggregate:

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
      ]
    }
  }}
])

The positional $ operator which can be used with a standard query is fine for matching a "single" element in array. But for multiple matches, or as in this case where the matches can be in "different" positions in each array, then then this sort of operation with $filter is required. Also using $arrayElemAt as example to just extract the single element from the array.

Upvotes: 1

Related Questions