mongodb - Mongo return first set of results found from 3 finds() -
is there way me search list of options until 1 of them comes results? or there better way in general find records following 3 queries:
{ "geotargets.countries.name": {$in: ["us"]}, "geotargets.countries.regions.name": {$in: ["ny", "nj"]}, "geotargets.countries.regions.cities.name": {$in: ["city 1", "city 2", "city 3"]} }, { "geotargets.countries.name": {$in: ["us"]}, "geotargets.countries.regions.name": {$in: ["ny", "nj"]} }, { "geotargets.countries.name": {$in: ["us"]} } i trying search , want this:
- first try find results match 1 of cities
- if nothing found try find results match 1 of regions
- again if nothing found try find results match on coutries
in application doing if search:
take slimmed down version of node (not real, purpose of visualization), way searching. doesn't seem best be. seems slow. there way in mongodb 1 query?
var results = db.campaigns.find({ "geotargets.countries.name": {$in: ["us"]}, "geotargets.countries.regions.name": {$in: ["ny", "nj"]}, "geotargets.countries.regions.cities.name": {$in: ["city 1", "city 2", "city 3"]}}); if(results.length == 0){ results = db.campaigns.find({ "geotargets.countries.name": {$in: ["us"]}, "geotargets.countries.regions.name": {$in: ["ny", "nj"]}}); if(results.length == 0){ results = db.campaigns.find({"geotargets.countries.name": {$in: ["us"]}}); } } console.log(results);
you make use of $or operator club these conditions , execute them.
the boolean $or operator of aggregation framework short circuit evaluation, i.e, if preceding condition satisfied, rest of conditions not executed against document.
var conda = { "geotargets.countries.name": {$in: ["us"]}, "geotargets.countries.regions.name": {$in: ["ny", "nj"]}, "geotargets.countries.regions.cities.name": {$in: ["city 1", "city 2", "city 3"]} }; var condb = { "geotargets.countries.name": {$in: ["us"]}, "geotargets.countries.regions.name": {$in: ["ny", "nj"]} }; var condc = { "geotargets.countries.name": {$in: ["us"]} }; and execute as:
db.campaigns.aggregate( [ {$match:{$or:[conda,condb,condc]}} ],function(err,data){ //callback }) $or uses short-circuit logic: operation stops evaluation after encountering first true expression.
although behavior of $or operator not documented when used query operator in find() query, try , see 1 more efficient data set.
Comments
Post a Comment