1
votes

I have a mongodb document like this,

{
  "_id" : ObjectId("4e8ae86d08101908e1000001"),
  "eId": 101,
  "about": "test",
  "tags" : [
          {"name": "jana"}, 
          {"name":"bala"}, 
          {"name":"jk"}, 
          {"name":"charles"}
   ]
}

I need to find all matched array elements, where the name matched with given array.

db.coll.find({"tags": {"$elemMatch": {"name": {"$in": [/^jana/i, /^charles/i] }}}})

for this query i got the following result

{
    "_id" : ObjectId("4e8ae86d08101908e1000001"),
    "tags" : [ 
        {
            "name" : "jana"
        }
    ]
}

$elemMatch query only return the first matched element, but i want all the matched array element like this,

{
    "_id" : ObjectId("4e8ae86d08101908e1000001"),
    "tags" : [ 
        {
            "name" : "jana"
        },
        {
            "name" : "charles"
        }
    ]
}

Is it possible to get the result like this?

note: i don't want any others fields, I want only the matched array elements along with _id

1

1 Answers

2
votes

You can use MongoDB Aggregation Pipeline:

db.coll.aggregate([
    {'$unwind': '$tags'},
    {'$match': 
        {"tags.name": 
            {"$in": [/^jana/, /^charles/i] }
        }
    },
    {'$group': 
        {
            '_id': '$_id',
            'tags': 
                {'$push': '$tags'}
        }
    }
])

Result : -

{
    "result" : [ 
        {
            "_id" : ObjectId("5538b214706a90c718f75a41"),
            "tags" : [ 
                {
                    "name" : "jana"
                }, 
                {
                    "name" : "charles"
                }
            ]
        }
    ],
    "ok" : 1
}