2

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

{ "_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”字段(在嵌套数组内) 。

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

4

1 回答 1

2

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

如果您正在运行 mongodb 2.2,则可以使用聚合框架 $unwind 嵌套数组,然后 $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);
} 

?>
于 2012-09-15T13:33:28.553 回答