Pankkaj
Pankkaj

Reputation: 129

search a particular key in mongodb collection using php

I have this mongodb collection.

{
"_id" : "3",
"SETTINGS" : {
    "PRIVACY" : {
        "ALLOW_SUGGESTIONS" : NumberLong(1),
        "BIRTHDAY" : NumberLong(0),
        "CONTACT_INFO" : {
            "PHONE" : NumberLong(0),
            "ADDRESS" : NumberLong(0)
        },
        "SEARCH_ENGINE" : NumberLong(0)
    }
}

I tried searching for a PHONE using php. Problem is that all the codes I have tried takes takes out a document and then I have to take out the key PHONE from document on my own.

My attempt was:-

$cursor=$collection->find(array('_id'=>'3'),array('SETTINGS'=>array('PRIVACY'=>array('CONTACT_INFO'=>array('PHONE')))));

foreach ($cursor as $document) { echo var_dump($document); }

It gives me output:-

Fatal error: Uncaught exception 'MongoCursorException' with message 'localhost:27017: Can't canonicalize query: BadValue Unsupported projection option: SETTINGS: { PRIVACY: { CONTACT_INFO: [ "PHONE" ] } }' in /var/www/html/ProjectTest/include/Profile Helper.php:114 Stack trace: #0 /var/www/html/ProjectTest/include/Profile Helper.php(114): MongoCursor->rewind() #1 /var/www/html/ProjectTest/profile.php(14): Profile->GetProfileInfo() #2 {main} thrown in /var/www/html/ProjectTest/include/Profile Helper.php on line 114

Summarizing my questions:-

Upvotes: 0

Views: 85

Answers (1)

Constantin Guay
Constantin Guay

Reputation: 1654

Would have been easier if you provided a code example of what output you'd like, and code of what you tried. You can try:

$db->$collection->find(array('SETTINGS.PRIVACY.CONTACT_INFO.PHONE' => 0))

This code will get you the document with phone equal 0

To return only the phone, you have to use projection:

$db->$collection->find(array('SETTINGS.PRIVACY.CONTACT_INFO.PHONE' => 0), array('_id' => 0, 'SETTINGS.PRIVACY.CONTACT_INFO.PHONE' => 1))

EDIT: According to the edition of your question, you lack the dot notation

Upvotes: 2

Related Questions