mongodb - subdocument query not containing values outside array with regex matching -



mongodb - subdocument query not containing values outside array with regex matching -

if have collection of recipes each item looks like:

{ name: "recipe 1", ingredients: [{ name: "dark chocolate", qty: "1 g" }, { name: "milk", qty: "2 g" }, { name: "unsalted butter", qty: "3 g" }] }

how can find recipes that:

have ingredient of name either contains milk or chocolate but do not contain other ingredients do not either contain milk or chocolate?

the illustration above not match query.

summary: need recipes contain milk, chocolate or both, nil else.

using regex look looks docs not containing ingredients of milk or chocolate (using technique here) , negating $not trick:

class="lang-js prettyprint-override">db.recipes.find({'ingredients.name': {$not: /^((?!(milk|chocolate)).)*$/}})

tested against:

class="lang-js prettyprint-override">{ "_id": objectid("5114f7b748994465c5b5c369"), "name": "recipe 1", "ingredients": [ { "name": "dark chocolate", "qty": "1 g" }, { "name": "milk", "qty": "2 g" }, { "name": "unsalted butter", "qty": "3 g" } ] } { "_id": objectid("5114f9f348994465c5b5c36a"), "name": "recipe 2", "ingredients": [ { "name": "dark chocolate", "qty": "1 g" }, { "name": "milk", "qty": "2 g" } ] } { "_id": objectid("5114fcec48994465c5b5c36b"), "name": "recipe 3", "ingredients": [ { "name": "milk chocolate", "qty": "1 g" } ] } { "_id": objectid("5114fd0e48994465c5b5c36c"), "name": "recipe 4", "ingredients": [ { "name": "soy", "qty": "1 g" } ] } { "_id": objectid("5114fd5248994465c5b5c36d"), "name": "recipe 5", "ingredients": [ { "name": "chocolate mud", "qty": "1 g" } ] }

it outputs:

class="lang-js prettyprint-override">{ "_id": objectid("5114f9f348994465c5b5c36a"), "name": "recipe 2", "ingredients": [ { "name": "dark chocolate", "qty": "1 g" }, { "name": "milk", "qty": "2 g" } ] } { "_id": objectid("5114fcec48994465c5b5c36b"), "name": "recipe 3", "ingredients": [ { "name": "milk chocolate", "qty": "1 g" } ] } { "_id": objectid("5114fd5248994465c5b5c36d"), "name": "recipe 5", "ingredients": [ { "name": "chocolate mud", "qty": "1 g" } ] }

mongodb

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -