2

I have numerous mongodb documents which are like

veg_doc1 = {........, veg_name: [bean, beans, brown bean, red carrot,radish, ......], ...... }

veg_doc2 = {........, veg_name : [bean, black beans, cabbage, brown beans, gorbanzo bean, organic carrot, red carrots,.....], .......... }

veg_doc3 = {...., veg_name: [cabbage, beatroot, beans], ........ }

Can I design a query which picks up all documents that has "bean" & say "carrot" as elements in "veg_name" field (basically one or multiple items with an "and" operation") ? I should be able to pick all those where each element (in this case bean and carrot) is a substring in the name (should include say bean, black beans, beans, carrot, red carrots etc and also those who have etc).

So if I query the above with ('bean', 'carrot') - I should get back both veg_doc1 and veg_doc2 but not veg_doc3.

Can someone help me here please? (I am using python/pymongo)

I am doing this

veg_regex = '[*bean|*carrot]' for sanc_doc in db.veg_collection.find({'vegetables':{'$in' {'$regex':veg_regex}}}): print(sanc_doc['vegetables'])

this doesn't work :-( Either I am doing something wrong in the regex or something wrong in the find query or may be both :-(

  • whatever is show as has answer, does not have an answer as they don't really talk about python/mongodb combo – Manjunath M Gowda Feb 07 '16 at 07:05
  • Also the question is no duplicate since the other one is asking – at least the answers regard it that way – for *single* valued fields. Funny enough that the answers stay correct for multi-valued fields. Nevertheless: no duplicate. – flaschbier Feb 07 '16 at 09:41
  • Oh, another hint (just saw your update): Don't use a `re`. Just write the regular expression, like in `c.find({ "veg_name" : { "$regex" : "^carrot" } })`. Also no `$in` required. Yes, this **is** an independent question on it's own right. No duplicate at all. – flaschbier Feb 07 '16 at 11:27
  • I actually loved to dig into detail here. Please refer to this Gist for more insight into your issue: https://gist.github.com/flaschbier/a3e9419428fc0b47006a – flaschbier Feb 07 '16 at 14:40

0 Answers0