1

I have an account document that looks like this:

_id: ###
email: string
password: md5(string)
altemail: [{ email: string
             verified: time},
           { email: string
             verified: time},
           { ... }]

And i would like to check for unique email before allowing a user to create an account. However, i would also like to permit saves for the current user _id.

My instinct is to use:

$db->users->find(array(
                    '$or' => array(array("email" => $email), 
                             array("altemail.email" => $email))
                    '_id' => array('$nin' => array($myID))
                )); 

But this isn't working for me. Could somebody show me how to set up a query roughly equivalent to mysql's:

SELECT *, count(_id) FROM users WHERE (email = $email OR altemail.email = $email) AND (_id != $myID);

Thanks guys.

4

2 回答 2

1

您可以使用$ne运算符而不是 $nin,因此您的查询将如下所示:

{
    "$or": [
        {
            "email": "test@test.com"
        },
        {
            "altemail.email": "test@test.com"
        }
    ],
    "_id": {
        $ne: "123456"
    }
}

php代码将是:

$db->users->find(array(
    '$or' => array(
                array("email" => $email), 
                array("altemail.email" => $email)
             ),
    '_id' => array('$ne' => $myID)
)); 
于 2013-07-10T17:27:50.047 回答
0

极好的!感谢所有帮助过的人。Miguel 的代码简洁、准确且相当优雅。这是对在我之后提出这个问题的任何人的最终解释:

$email = "name@domain.com";                       //example email
$myID = new MongoId("51dc6628e8602982ae33ef77");  //example id

$db->users->find(array(
'$or' => array(
            array("email" => $email), 
            array("altemail.email" => $email)
         ),
'_id' => array('$ne' => $myID)
)); 

此查询将:

  1. 为当前存储了电子邮件(不是重复)的用户返回(空)
  2. 返回(非空)为试图存储不明确的电子邮件地址(重复)的用户

再次感谢大家。

于 2013-07-12T21:32:41.567 回答