1

How to search comma separated values in MongoDB using PHP with comma separated input values?

Ex: In collection1 I am storing the values with comma separated and now I want to search that column with comma separated values:

{service_list: 'a, b, c'}

Now I want to search that field with (a,d,e).

If we store in array we can search easily but there is no chance to change the DB structure. How can I solve this issue?

3
  • Did you try something like that db.collection1.find({"service_list": /.*a.*.d.*/}) Commented Mar 23, 2017 at 9:36
  • Thanks for your reply, I have tried just now it's not getting all matched documents Commented Mar 23, 2017 at 10:01
  • You really need to change that DB structure. The long-term downside of sticking with a bad database design will outweight the short-term pain of rectifying the structure. Commented Mar 23, 2017 at 19:10

1 Answer 1

0

You can use $regex

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find(
 array('service_list' => array('$regex' => 'something'))
);

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

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.