2

I want to make a query in mongodb for searching a string in another string. Now the use case is I have document like:

{
    "names":"[John,Mike,Stephen,Rock]"
}

Now I want to make a filter which will search for :

  1. Case-1: If John is present in names or not
  2. Case-2: If John and Mike both are present in this string

I am quite new to mongodb. I went through many posts, but I haven't got any satisfactory results as of now. Some are using regex or text search.Can anyone help in making the query

2 Answers 2

2

You can try below queries which uses regex pattern :

Case 1 : Check names string field contains a word John.

db.collection.find({ names: /John/})

Case 2 : Check names string field contains both John & Mike words.

db.collection.find({ names: {$all : [/John/, /Mike/]}})

I would suggest to have index on names field & try to use text-search if possible.

Ref : $all

Sign up to request clarification or add additional context in comments.

3 Comments

whoami , how we can check the opposite that John is not present in names ? Can you help in that too . :)
@Anshul : You need to use $nin instead of $all. Something like this db.collection.find({ names: {$nin : [/John/]}})..
Ok , that works , thank you so much for the help !! :)
0

Use the $in Operator to Match Values in an Array in MongoDb:

Suppose the collection inventory contains documents that include the field tags, as in the following:

{ _id: 1, item: "abc", qty: 10, tags: [ "school", "clothing" ]}

Then, the following find() operation will get tags field which holds an array with at least one element matching either "appliances" or "school".

db.inventory.find({ tags: { 
        $in: ["appliances", "school"] } 
});

For your use case 1:

db.users.find({names : "John"});

For your use case 2:

db.users.find({ names: { 
       $in: ["John", "Mike"]
 } });

1 Comment

But here its not the array its string, would searching using in will work in this case as well ?

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.