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?

0

2 Answers 2

2

Try this query

db.collection.find({"name": /.*cl.*/})
Sign up to request clarification or add additional context in comments.

3 Comments

Tks bro. Im not sure it is too simple. I think the query need some operations like "$or" and "$like". Tkz u again!
This would be case sensitive. An i after the regex should make this case insensitive
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" ] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.