简体   繁体   中英

MongoDB: Find all matched array element from single document

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM