![](/img/trans.png)
[英]How to click on a table entry and search for it in another mongodb collection ( php / jquery )
[英]How to find a mongodb collection entry by ObjectId in php
我有一個mongodb數據庫,其中包含兩個連接的集合。
第一個數據集如下所示:
{
"_id": ObjectId("5326d2a61db62d7d2f8c13c0"),
"reporttype": "visits",
"country": "AT",
"channel": "wifi",
"_level": NumberInt(3)
}
ObjectId連接到第二個集合中的幾個數據集,如下所示:
{
"_id": ObjectId("54c905662d0a99627efe17a9"),
"avg": NumberInt(0),
"chunk_begin": ISODate("2015-01-28T12:00:00.0Z"),
"count": NumberInt(15),
"max": NumberInt(0),
"min": NumberInt(0),
"sum": NumberInt(0),
"tag": ObjectId("5326d2a61db62d7d2f8c13c0")
}
如您所見,第一個數據集中的“ _id”與第二個數據集中的“標簽”相同。
我想在php中編寫一個例程,該例程從第一個集合中獲取ID,並在第二個集合中的特定時間范圍內按它們查找要刪除的數據集。
我可以從第一個集合中獲取ID,但是我懷疑我在第二個集合的查詢中錯誤地使用了該ID,因為沒有發現或刪除任何內容。
代碼如下:
// select a collection (analog to a relational database's table)
$tagCollection = $db->tags;
$orderCollection = $db->orders;
// formulate AND query
$aTagCriteria = array(
'reporttype' => new MongoRegex('/[a-z]+/'),
);
// retrieve only _id keys
$fields = array('_id');
$cursor = $tagCollection->find($aTagCriteria, $fields);
$startOfTimeperiod = new MongoDate(strtotime('2015-01-05 00:00:00'));
$endOfTimeperiod = new MongoDate(strtotime('2015-01-07 13:20:00'));
// iterate through the result set
foreach ($cursor as $obj) {
echo '_id: '.$obj['_id'].' | ';
// Until here all is ok, I get the _id as output.
$aOrdercriteria = array(
'tag' => new MongoId($obj['_id']),
'date' => array(
'$lte' => $endOfTimeperiod,
'$gte' => $startOfTimeperiod
),
);
$iCount = $orderCollection->count($aOrdercriteria);
if ($iCount > 0) {
echo PHP_EOL.$iCount.' document(s) found.'.PHP_EOL;
$result = $orderCollection->remove($aOrdercriteria);
echo __FUNCTION__.'|'.__LINE__.' | '.json_encode($result).PHP_EOL;
echo 'Removed document with ID: '.$aOrdercriteria['tag'].PHP_EOL;
}
}
搜索條件的正確方法是什么,以便它查找具有先前找到的ID的標記對象?
PS:我嘗試過
'tag' => $obj['_id'],
代替
'tag' => new MongoId($obj['_id']),
這也不起作用。
所以必須改變兩件事。
第一個就像EmptyArsenal暗示的那樣:
tag' => new MongoId($obj['_id']),
是錯誤的,因為$ obj ['_ id']已經是一個對象。
所以
'tag' => $obj['_id'],
是正確的。 而且,如果我將條件從“日期”更改為“ chunk_begin” yahooo,...它將起作用。 愚蠢的我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.