Question

I need to find a couple of documents which have specific colors. I've search this place and was able to construct the following query:

db.tasks.find({$or: { color:  {$all: ['e4oqPeoBTJtCpG53K', 'cvmQv7vQHunPnmqPz'] }}});

What I'm trying here is to find all documents which have a color of e4o... and cvmQ.. But this doesn't work at all. Any suggestions what I do wrong ?

Was it helpful?

Solution

If you just want to find the the documents that only contain the specified color values you can use this form with the $and operator and the use of $size:

db.tasks.find({ "$and": [
    { "color": "e4oqPeoBTJtCpG53K" },
    { "color": "cvmQv7vQHunPnmqP"' },
    { "color": { "$size": 2 } }

]}

And this simplifies a little with the MongoDB 2.6 and upwards releases by actually fixing the proper use of $all as an operator so that it behaves much like logical $and but with better syntax:

db.tasks.find({ "$and": [
   {"color": {
       "$all": [ "e4oqPeoBTJtCpG53K", "cvmQv7vQHunPnmqPz" ]
   },
   { "color": { "$size": 2 } }

]}

Or even another way of writing the same thing is like this using logical $or:

db.tasks.find({ "$and": [
   "$or": [
       {"color": [ "e4oqPeoBTJtCpG53K", "cvmQv7vQHunPnmqPz" ]  },
       {"color": [ "cvmQv7vQHunPnmqPz", "e4oqPeoBTJtCpG53K" ]  }
   ],
   { "color": { "$size": 2 } }
]}

If the array must contain both of those elements and possibly more then the simple form is with the $and constraint alone:

db.tasks.find({ "$and": [
    { "color": "e4oqPeoBTJtCpG53K" },
    { "color": "cvmQv7vQHunPnmqP"' }
]}

And if "any" element in any document this is a logical $or best specified with the $in operator

db.tasks.find({
    "color":  {
        "$in": ["e4oqPeoBTJtCpG53K", "cvmQv7vQHunPnmqPz"] 
    }
})

Whatever you actually want to do, there should be enough options there.

Please also note that these will work with the "server side" implementation, but mileage on the "client" side using "minimongo" may differ due to the support in that client side code.

OTHER TIPS

Try without the $or, and using $in (If you're looking for documents which have a colour that is listed), ($all if you want documents with all the colours listed).

db.tasks.find({ color:  {$in: ['e4oqPeoBTJtCpG53K', 'cvmQv7vQHunPnmqPz'] }});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top