In mongodb bash I can do this:
db.collection.find({'field1': /^value1/, 'field2': /^value2/, 'field2': /^value3/});
It is very convenient when field2
is an array. The alternative is:
db.collection.find({'$and': [
{'field1': /^value1/},
{'field2': /^value2/},
{'field2': /^value3/}
]});
... which is inconvenient.
But I can't use the first query in php because php array keys must be unique. Is there any way to do this query in php?
You can use the $all
operator which is equivalent to an $and
operation of the specified values; i.e. the following statement:
{ "field2": { "$all": [ /^value2/, /^value3/ ] } }
is equivalent to:
{ "$and:" [ { "field2": /^value2/ }, { "field2": /^value3/ } ] }
Thus your final query would be
db.collection.find({
"field1": /^value1/,
"field2": { "$all": [ /^value2/, /^value3/ ] }
});