Calamity Jane
Calamity Jane

Reputation: 2666

How to find a mongodb collection entry by ObjectId in php

I have a mongodb database which contains two connected collections.

The first one has a dataset which looks like this:

{
"_id": ObjectId("5326d2a61db62d7d2f8c13c0"),
"reporttype": "visits",
"country": "AT",
"channel": "wifi",
"_level": NumberInt(3)
}   

The ObjectId is connected to several datasets in the second collection which look like this:

{
"_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")
}   

As you can see it the "_id" from the first dataset the same as the "tag" from the second.

I want to write a routine in php which gets the ids from the first collection and finds by them datasets in a certain timeframe in the second collection for deletion.

I get the id from the first collection ok, but I suspect I use it wrongly in the the query for the second collection because nothing is ever found or deleted.

Code looks like this:

// 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;
    }
}

What is the correct way for the search condition so it looks for tag Objects with the previously found id?

PS: I tried

'tag'  => $obj['_id'],

instead of

'tag'  => new MongoId($obj['_id']),

which didn't work either.

Upvotes: 1

Views: 1503

Answers (1)

Calamity Jane
Calamity Jane

Reputation: 2666

So two things had to be changed.

The first one was like EmptyArsenal hinted:

tag'  => new MongoId($obj['_id']), 

is wrong since $obj['_id'] is already an object.

So

'tag'  => $obj['_id'],

is correct. And if I change my condition from "date" to "chunk_begin" yahooo.... it works. Stupid me.

Upvotes: 1

Related Questions