1

我有一个看起来像这样的 Mongo Collection

{
"_id": ObjectId("0000000000000123"),
"user_id": NumberLong(000010),
"location": {
    "addresses": [{
            "number": NumberLong(4410),
            "street": "Test Drive",
            "county": "New York County",
            "city": "New York",
            "state": "NY",
            "zip": "00001",
            "links": [{
                    "image": "http://www.google.com/test",
                    "datetime": " 11/24/1952"
                }, {
                    "image": "http://www.google.com/test2",
                    "datetime": " 11/24/1990"
                }
            ]
        }
    ]
}
}

我需要能够在链接数组中搜索带有 www.google.com 的文档,并能够将其更改为 www.yahoo.com

我尝试了几个版本的 mongo 更新但没有成功

$search_string = new MongoRegex("/www.google.com/i");
$collection->update(
        array('location.addresses.links.image' => $search_string),
        array('$set' => array('location.addresses.$.links.$.image' => '')),
        array("multiple" => true)
    );
4

1 回答 1

0

所以经过更多的挖掘,我发现更新位置运算符($)只能使用一层深度。

所以我决定通过引用使用 foreach 语句来完成我需要做的事情

        $collection = new MongoCollection($this->db, 'users');

        $search_string = new MongoRegex("/www.google.com/i");

        $cursor = $collection->find(array('location.addresses.links.image' => $search_string));

        foreach ($cursor as $doc)
        {
            foreach ($doc['location']['addresses'] as &$address)
            {
                foreach($address['links'] as &$link)
                {
                    $link['image'] = str_replace('www.google.com', 'www.yahoo.com', $offender['image']);
                }
            }

            $collection->update(array("_id" => $doc['_id']), $doc);
        }
于 2013-05-16T13:35:02.600 回答