0

I have a schema like so:

{
  color: [
    "red",
    "yellow"
  ]
  ...
}

Any of the docs in the collection could have any number of colours (main seven by name).

In mongoose I try and find any documents that match, "red" or "blue" or "green" and return those documents that contain any of those three colours, I do not want to filter out other colours such as "yellow". I tried mongodb $in operator like so

model.find({ colors: { "$in": ["red", "blue", "green"] } })
  .limit(50).exec((err, data) => {
    if (err) throw err;
    else console.log(data);
});

But, when I run this I am getting nothing in return even though there would be tonnes that have at least a colour of red, blue, or green.

Id like to get the documents where any of the documents color[] matches any of the comparisons color[].

EDIT:

I tried:

var colors = ["red", "blue"];
var obj = {};

obj.$match = { 'color': { '$in': colors } };
obj.$match = { 'color': { '$elemMatch': colors } };
obj.$match = { 'color.$': { '$in': colors } };
obj.$match = { 'color.*': { '$in': colors } };

obj = { colors: { $elemMatch: { $in: colors } } };

model.find(obj, ...);

And other combinations based off that post, but I am still getting nothing in return.

I basically want something like this:

var CheckIfAnyInArray = (obj) => {
  obj.color.forEach((i) => {
    if (colors.indexOf(i) > -1) return true;
  };
  return false;
};

EDIT: Solution...

So, I am an idiot, the problem is not my calls its a typo. The document schema is 'colors' not 'color'. I kept on overlooking the 's' and not realising it.

So this solution works:

model.find({ colors: { $in: colors } })...;

Very stupid mistake on my part.

Drew
  • 1,171
  • 4
  • 21
  • 36
  • By using `.find({ "data.thing": "blue" })` or course. Or where "either" it would be using `$in` as : `.find({ "data.thing": { "$in": ["red","green","blue"] } })` Or if you want a "specific index" then `.find({ "data.1.thing": "blue" })` where `1` is the position ( starting from 0 ) of the "second" index in the array. – Neil Lunn Jul 20 '17 at 02:53
  • Ok the duplicate that Neil marked anwsers my second question. – Drew Jul 20 '17 at 03:20

0 Answers0