Reputation: 1260
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?
Upvotes: 3
Views: 53
Reputation: 103425
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" ] }
Upvotes: 1