Aaron
Aaron

Reputation: 381

"and" within "or" in PHP's MongoDB query

mongodb and or combo Similar to this except I'm using php and getting [MongoCursorException] $or array must contain objects.

Also read this http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

How can one nest an "AND" inside of an "OR" in MongoDB via PHP? Here is my conditions argument (via var_export):

'group_id' => '4eec13b5-aeb4-48ee-9619-449125af0e18',
'$or' => 
array (
  0 => 
  array (
    0 => 
    array (
      'active' => 0,
      'user_id' => '4eea7b76-5d34-4036-8344-120c0aaa1bdc',
    ),
  ),
  1 => 
  array (
    1 => 
    array (
      'active' => 1,
    ),
  ),
)

Need list of posts that are in a group id AND are active OR (belong to the user AND are not active).

Extremely easy in SQL but whichever variation I try in the MongoDB via PHP query I get the $or error. Is this possible? Is an $and required?

Upvotes: 2

Views: 2876

Answers (1)

Nat
Nat

Reputation: 3717

your query is just incorrect. In JSON, it would look like

{ 
   "group_id" : "4eec13b5-aeb4-48ee-9619-449125af0e18",
   "$or" : [ 
                    [ { "active" : 0, "user_id" : "4eea7b76-5d34-4036-8344-120c0aaa1bdc" } ],
                    [ null, { "active" : 1 } ] 
           ]
}   

for group id AND are active OR (belong to the user AND are not active), it should be represented somewhat as :

{ 
   "group_id" : "4eec13b5-aeb4-48ee-9619-449125af0e18",
   "$or" : [ 
                    { "active" : 0, "user_id" : "4eea7b76-5d34-4036-8344-120c0aaa1bdc" },
                    { "active" : 1 } 
           ]
}   

More or less, it will look like this in PHP

array(
'group_id' => '4eec13b5-aeb4-48ee-9619-449125af0e18',
'$or' => 
     array (
        0 => 
           array (
               'active' => 0,
               'user_id' => '4eea7b76-5d34-4036-8344-120c0aaa1bdc',
           ),
        1 => 
           array (
               'active' => 1,
           )
     ),
)

Upvotes: 5

Related Questions