Search code examples
mongodbphp-mongodbmongodb-query

mongoDB - if row does not have


I have a database collection, with 1000 CRN numbers which I need to issue to our customers.

We use MongoDB, and I would like to issue CRN number to an Email account.

so here is our current JSON

{
"CRN":516612
}

what I need to do in PHP is do a find where it does not have a "email":"EMAIL ACCOUNT"

I can't get the normal find() working.


Solution

  • To select a document which doesn't have an email field set you would do:

    db.collection.find({"email":{$exists:false}})
    

    To store an email address atomically in a document that matches this condition you would do:

    db.collection.update({"email":{$exists:false}},{$set:{"email":"new@email.com"}})
    

    If you need to get back the CRN that you just assigned the email to, you would use findAndModify:

    q = db.collection.findAndModify({query:{email:{$exists:false}},
                                     update:{$set:{email:"new@email.com"}}})
    

    q will have the document that you just modified (with CRN and _id but not with email - you can use an option to get back email as well.