dongxiane0395 2011-12-30 01:33
浏览 29
已采纳

在PHP的MongoDB查询中“和”在“或”中

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?

  • 写回答

1条回答 默认 最新

  • dongqian1893 2011-12-30 05:25
    关注

    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,
               )
         ),
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?