Mongodb / PHP如果不存在,如何在嵌套数组中插入?

时间:2012-09-15 06:36:50

标签: php mongodb

我的收藏品的内容是这种形式,

{ "_id" : ObjectId("50535036381ef82c08000002"),"source_references" : [
    {
            "_id" : ObjectId("50535036381ef82c08000001"),
            "name" : "abc",
            "key" : "123"
    }]
}

现在我想在“source_references”中插入另一个数组,如果嵌套数组中不存在名称和键,否则不插入。这是我想要的结果,

{ "_id" : ObjectId("50535036381ef82c08000002"),"source_references" : [
    {
            "_id" : ObjectId("50535036381ef82c08000001"),
            "name" : "abc",
            "key" : "123"
    }
    {
            "_id" : ObjectId("50535036381ef82c08000003"),
            "name" : "reuters",
            "key" : "139215"
     }]
}

这是我尝试过的:

$Update_tag = array('$addToSet' => array("source_references.$" => array("name" => "reuters", "key" => $r_id)));
$mycollection->update(array("_id" => $id), $Update_tag);

但是我无法在嵌套数组中插入另一个数组。此外,我只想在 source_references 中插入新数组时创建“_id”字段(嵌套数组内)。

我哪里错了?希望我对我的问题很清楚。

1 个答案:

答案 0 :(得分:2)

这很棘手,因为每个子文档都有唯一的密钥。因此,您无法使用$ elemMatch来检查密钥/名称对是否已存在。

如果您正在运行mongodb 2.2,则可以使用聚合框架来展开嵌套数组,然后使用$ match作为键/名称对,并仅在搜索返回为空时插入新元素。

这是php代码:

<?php

// connect
$m = new Mongo('localhost:27017');

// select a database and collection
$db = $m->test;
$collection = $db->coll;

// sub-doc to insert if key/name pair doesn't exist
$doc = array('key'=>'12345', 'name' => 'abcde');

// aggregation command (can use $collection->aggregate for driver version 1.3.0+)
$cursor = $db->command(array('aggregate' => 'coll', 'pipeline' => array(
    array('$unwind'=>'$source_references'),
    array('$match' => array('source_references.name' => $doc['name'], 
                            'source_references.key' => $doc['key']))
)));

// if sub-doc doesn't exist, insert into main doc with this objectId
$objectId = '50535036381ef82c08000002';

if (count($cursor['result']) == 0) {
    // insert document with a new ObjectId (MongoId)
    $update_tag = array('$addToSet' => array("source_references" => array("_id" => new MongoId(), "name" => $doc['name'], "key" => $doc['key'])));
    $collection->update(array("_id" => new MongoId($objectId)), $update_tag);
} 

?>