Michael
Michael

Reputation: 345

get document from array in mongodb with php

I have the following Document

{
    "_id" : ObjectId("608d5b653979af6a8555f643"),
    "eMail" : "[email protected]",
...
    "billing" : [ 
        {
            "company" : "MoskitoFactory",
            "salutation" : "1",
            "firstname" : "Ben",
            "lastname" : "Water",
            "address_line_1" : "Black 1235",
            "address_line_2" : "",
            "address_line_3" : "",
            "zip" : "555",
            "city" : "Onecity"
        }, 
        {
            "company" : "Witchcraft4U",
            "salutation" : "1",
            "firstname" : "Mike",
            "lastname" : "Phone",
            "address_line_1" : "Sea 4445",
            "address_line_2" : "",
            "address_line_3" : "",
            "zip" : "12345",
            "city" : "Somecity"
        }
    ]
}

how do I get the billing address with array index 0?

I thought this way

$billing = $db->buyer->findOne([

    '_id' => new MongoDB\BSON\ObjectID($_SESSION['uid'])
],[
    
    'projection' => ['billing.0' => 1]
]
);

var_dump($billing->billing);

but it gives me only

object(MongoDB\Model\BSONArray)#28 (1) {
    ["storage":"ArrayObject":private]=>
    array(2) {
      [0]=>
      object(MongoDB\Model\BSONDocument)#26 (1) {
        ["storage":"ArrayObject":private]=>
        array(0) {
        }
      }
      [1]=>
      object(MongoDB\Model\BSONDocument)#27 (1) {
        ["storage":"ArrayObject":private]=>
        array(0) {
        }
      }
    }
  }

I don't know if the query is correct and I simply don't know how to display the result. But If I read this right it gives me two objects back instead of one (billing address No 0)

Upvotes: 1

Views: 203

Answers (1)

turivishal
turivishal

Reputation: 36104

try $slice operator to get specific element from array of object, this will return single element object in array.

$billing = $db->buyer->findOne([
    '_id' => new MongoDB\BSON\ObjectID($_SESSION['uid'])
],[   
    'projection' => ['billing' => ['$slice' => [0,1]]]
])

Playground


If you want to get object only instead of array try $arrayElemAt operator to get object from specific index,

This is Starting in MongoDB 4.4, you can use aggregation operator in find / findOne method's projection,

$billing = $db->buyer->findOne([
    '_id' => new MongoDB\BSON\ObjectID($_SESSION['uid'])
],[   
    'projection' => ['billing' => ['$arrayElemAt' => ['$billing', 0] ]]
])

Playground

Upvotes: 1

Related Questions