mongodb php查询只返回子对象项

时间:2014-01-13 04:48:55

标签: php mongodb

我正在尝试使用PHP复制mongodb查询。

以下查询使用mongo shell。

db.user.find({"_id": ObjectId("52d1cedfb1c097b41800055e"), "address.type": "home"},    

{"_id": 0, "address.coordinent.longitude": 1, "address.coordinent.latitude": 1,  "address.zipcode": 1})

它返回:

{ "address" : [         {       "zipcode" : "84123",    "coordinent" : {
"longitude" : -111.908978,      "latitude" : 40.63147499999999 } } ] }

我确实收到了以下结果文件:

$db->user->findOne(array( "_id" => $mongoID))

但以下使用PHP的尝试不起作用:

$db->user->findOne(array( "_id" => $mongoID), array("address->type" => "home"},{"_id": 0, "address->coordinent->longitude" => 1, "address->coordinent->latitude" => 1,  "address->zipcode" => 1}))

$db->user->findOne(array( "_id" => $mongoID), array("address[type]" => "home"},{"_id": 0, "address[coordinent][longitude]" => 1, "address[coordinent][latitude]" => 1,  "address[zipcode]" => 1}))

PHP中查询的正确格式是什么?

1 个答案:

答案 0 :(得分:0)

您需要在mongo shell示例中使用与PHP相同的dot notation

(未经测试的)查询应该类似于:

<?php
    $query = array(
        "_id" => $mongoID,
        "address.type" => "home",
    );

    $projection = array(
        "_id" => 0,
        "address.coordinent.longitude" => 1,
        "address.coordinent.latitude" => 1,
        "address.zipcode" => 1,
    );

    $db->user->findOne($query, $projection);
?>