Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB $or query in PHP

Tags:

find

php

mongodb

I can't figure out for the life of my to select from a collection with the or parameter. It's not working at all for me and I can't really find any documentation on it for php.

Here is my example code that doesn't return anything even though they exist in the collection:

$cursor = $products->find(
    array(
        '$or' => array(
            "brand" => "anti-clothes",
            "allSizes" => "small"
        )
    )
);
like image 615
Andrew Avatar asked Sep 17 '11 00:09

Andrew


People also ask

What is $or in MongoDB?

MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array.

Can I use MongoDB with PHP?

You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components: The extension , which provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.

How do I use $in in MongoDB?

This operator is used to select those documents where the value of the field is equal to any of the given value in the array. And if the field contains an array, then this operator selects only those documents whose field contains an array that holds at least one item that matches a value of the specified array.

How do I search in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.


1 Answers

The $or operator lets you use boolean or in a query.
You give $or an array of expressions, any of which can satisfy the query.

You provided only one element in the array. Use:

find(array('$or' => array(
  array("brand" => "anti-clothes"),
  array("allSizes" => "small")
)));
like image 178
Karoly Horvath Avatar answered Sep 20 '22 14:09

Karoly Horvath