【问题标题】:How to get a specific object from array of objects inside specific MongoDB document?如何从特定 MongoDB 文档中的对象数组中获取特定对象?
【发布时间】:2012-06-28 17:59:15
【问题描述】:

我的 MongoDB 文档有结构:

{
    _id : "12345",
    name : "foo",
    object : {
        array_of_objects : [{
            id : 507,
            name : "some name",
            dt : "2012-06-27 16:35:50"
        },{
            id : 506
            name : "some other name",
            dt : "2012-06-21 16:09:05"
        },
        …
        ]
    }
}

我需要从 array_of_objects 中获取一个对象,该对象具有指定 name 的文档的特定 ID。我使用php并尝试执行下一个代码:

$collection->find(array('name' => 'foo', 'object.array_of_objects.id' => 507));

它返回 array_of_objects 的所有元素,而不是 id 507 的元素。 之后我尝试使用 $elemMatch 进行查询:

$collection->find(array('name' => 'foo', 'object.array_of_objects' => array('$elemMatch' => array('id' => 507))));

但它的返回值相同。 :( 我的 MongoDB 版本 2.0.6。请帮忙。

【问题讨论】:

标签: php mongodb


【解决方案1】:

此问题已解决,将在 MongoDB 版本 2.2 中提供,下一个稳定版本:https://jira.mongodb.org/browse/SERVER-828

我刚刚使用 MongoDB 2.1.2(不稳定,开发版本)进行了尝试:

示例文档:

{ "_id" : 1, "object" : { "array" : [ { "id" : 507, "name" : "Jenna" }, { "id" : 506, "name" : "Matt" } ] } } 

查询:

db.food.find({_id:1, "object.array.id":506},{_id:0, "object.array.$":1})

结果:

{ "object" : { "array" : [ { "id" : 506, "name" : "Matt" } ] } }

【讨论】:

  • 大家好消息! 8) 谢谢@Jenna!
【解决方案2】:

您无法使用 MongoDB 执行此操作:例如,MongoDB 不会深入到特定文档以从数组中提取项目,您必须自己执行此操作。

现在 PHP 驱动程序可能会做更多的工作,我不知道 -- 我说的是 MongoDB 核心查询。

【讨论】:

  • 您可以返回字段的子集 - 查看 MongoDB 文档:mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields
  • @Jenna 是的,你是对的——但是基于数组的值的特定项目?
  • 据我了解,可以通过获取整个对象数组并使用 PHP 搜索所需项目,或者使用 MapReduce 来完成,对吧?
【解决方案3】:

所以,我用 MapReduce 做到了。希望这可以节省一些人的时间和精力。

$name = 'foo';
$id = 507;

$mongo = new Mongo('…');

$db = $mongo->my_db;

$map = new MongoCode('function(){'.
    'this.object.array_of_objects.forEach(function(obj){'.
        'if (obj.id == '.$id.')'.
            'emit(1, obj);'.
    '});}'
);

$reduce = new MongoCode('function(k,v){ return [k,v]; }');

$response = $db->command(array(
    'mapreduce' => 'my_collection', 
    'map' => $map,
    'reduce' => $reduce,
    'query' => array('name' => $name),
    'out' => array('inline' => 1)
));

var_dump($response['result']);

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 2018-11-05
    相关资源
    最近更新 更多