我正在尝试使用新字段更新mongoDB集合中的每个文档。这通过其mongoID选择特定文档然后插入特定字段时工作正常但是当我尝试在循环中执行它时它会以某种方式停止工作。见下面的代码。任何人都知道为什么会失败?
$m = new MongoClient();
$db = $m->selectDB('SocialMedia');
$collection = new MongoCollection($db, 'testcoord');
$myC = $collection->find();
foreach($myC as $tweet){
$testCoord = array($tweet['coordinates']['coordinates'][0],$tweet['coordinates']['coordinates'][1]);
foreach ($areaArray as $area) {
if (pointInPolygon($area,$testCoord)){
$collection->update(array('_id'=>$tweet['_id']),array('$set' => array('city_area' => $area['areaName'])));
}
}
}
答案 0 :(得分:0)
您的示例代码未满,因为没有$ areaArray和pointInPolygon()的定义,因此很难看出您的目标是什么。
但请注意,您在foreach周期中多次更新同一文档,因此您的 city_area 字段每次都在重写(这就是$set运算符的工作方式)。
// this is how your updates go
$collection->update(['_id' => 'tweet_1'], ['$set' => ['city_area' => 'value1']);
$collection->update(['_id' => 'tweet_1'], ['$set' => ['city_area' => 'value2']);
$collection->update(['_id' => 'tweet_1'], ['$set' => ['city_area' => 'value3']);
// now your document with id = 'tweet_1' contains 'city_area' = 'value3'
// 'value1' and 'value2' are rewrited
如果要在一个字段中存储多个值,请改用$addToSet运算符。 否则,请根据您的目标修复代码。
例如,此代码完美运行:
$mongoClient = new MongoClient();
$db = $mongoClient->selectDB('Test');
$collection = new MongoCollection($db, 'test_collection');
// inserting 5 documents with values from 1 to 5
foreach (range(1, 5) as $value) {
$collection->insert(
['value' => $value]
);
}
// find and update each document with new value
$cursor = $collection->find();
foreach ($cursor as $doc) {
$newValue = 2; // insert here your code, calculating new value for each document
$collection->update(
['_id'=>$doc['_id']],
['$set' => ['value' => newValue]]
);
}
// now we have 5 documents with field 'value' equals 2 each