kz_sergey kz_sergey - 2 months ago 12
PHP Question

How to enter equal keys in mongodb query via php?

In mongodb bash I can do this:

db.collection.find({'field1': /^value1/, 'field2': /^value2/, 'field2': /^value3/});

It is very convenient when
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

    "field1": /^value1/, 
    "field2": { "$all": [ /^value2/, /^value3/ ] }