【问题标题】:Mongodb array in array数组中的MongoDB数组
【发布时间】:2014-02-07 11:47:39
【问题描述】:

这是我的 mongo 文档,如何在 PHP 中获取 hud 到 $_id = ("52ee9fef94ffc1f7a0dd0a55") 的对象或数组?

 "_id" : ObjectId("52ee9fef94ffc1f7a0dd0a55"),
 "lvl" : 2,
 "required_xp" : 100,
 "rewards" : {
         "hud" : [
                 {
                         "type" : "food",
                         "amount" : 50
                 },
                 {
                         "type" : "soft",
                         "amount" : 100
                 }
         ],
         "inventory" : [
                 {
                         "id" : 24,
                         "amount" : 1
                 }
         ]
 },
 "xp_next_lvl" : 110

【问题讨论】:

  • 我试图更好地理解这个问题。您想知道如何通过 id 从您的集合中选择特定文档吗?

标签: php arrays mongodb-php


【解决方案1】:

要仅选择与特定 _id 匹配的文档的 rewards.hub 字段,您可以将 findOne 与投影一起使用:

<?php
    $m = new MongoClient();
    $db = $m->selectDB('mydb');
    $collection = new MongoCollection($db, 'mycollection');

    // Search criteria
    $query = array('_id' => new MongoId("52ee9fef94ffc1f7a0dd0a55"));

    // Projection (fields to include)
    $projection = array('_id' => false, 'rewards.hud' => true);

    $hud = $collection->findOne($query, $projection);
    var_dump($hud);
?>

var_dump 的示例输出(为便于阅读而整理):

array(1) {
  ["rewards"] => array(1) {
        ["hud"] => array(2) {
              [0] => array(2) {
                    ["type"] => string(4) "food"
                    ["amount"] => float(50)
                  }
              [1] => array(2) {
                    ["type"] => string(4) "soft"
                    ["amount"] => float(100)
                  }
            }
      }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2015-01-10
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多