Search a String in another array like string in mongodb

Viewed 63

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

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

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"]
 } });
Related