3

I have a document with property is an array like:

{
  name: ['Clark', 'Memphe', 'Alberto', 'Traicl']
}

I want query with keyword = 'cl' and I purpose the return will be

['Clark', 'Traicl']

How I can query with this conditions?

Thanh Dao
  • 1,218
  • 2
  • 16
  • 43

2 Answers2

2

Try this query

db.collection.find({"name": /.*cl.*/})
Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45
1

One approach you can take is to use the aggregation framework. The aggregation pipeline would have the initial step $match that filters the documents with the name array that matches the regex pattern. Further down the pipeline you would need an $unwind operator which essentially turns one document into many. Another $match pipeline stage would be necessary to filter those deconstructed array documents and then a final $group step to aggregate the matched documents through the $push accumulator operator. So the following pipeline operation:

var re = new RegExp(/.*cl.*/i)
db.collection.aggregate([
    {
        "$match": { "name":  re }
    },
    {
        "$unwind": "$name"
    },
    {
        "$match": { "name": re }
    },
    {
        "$group": {
            "_id": null,
            "name": {
                "$push": "$name"
            }
        }
    }
])

will give the result:

{ "_id" : null, "name" : [ "Clark", "Traicl" ] }
chridam
  • 100,957
  • 23
  • 236
  • 235