user3159535
user3159535

Reputation: 41

Mongo DB query issue

I am beginner in Mongo DB. I wrote the query see below for your further reference.

My Query is

$result =  $this->likes->find(array("post_id" => $post_id));

In that my table name is "likes" having the field name post_id, I am passing the $post_id (its my dynamic value example $post_id= "55b86fb60fdd9419128b4567").

But I cannot get my expected result from the below query, if I pass the $post_id is static means I got it my desired result.

Thanks advance for your help

Upvotes: 2

Views: 95

Answers (4)

Sunil Rawat
Sunil Rawat

Reputation: 709

Try this:

$result = $this->likes->find(array("post_id" => new\ MongoId($post_id)));

Upvotes: 0

RajeshPalande
RajeshPalande

Reputation: 19

Try This:

function connection($tableName){        
    // Connect to Mongo
    //$this->connection = new MongoClient('localhost:27017'); //for linux
    $this->connection = new Mongo('localhost:27017'); // for window

    // Select a database
    $this->db = $this->connection->databaseName;

    // Select a collection
    $this->posts = $this->db->$tableName;
}

$this->connection('likes'); // likes is collection name
$id= "55b86fb60fdd9419128b4567";
$members = $this->posts->find(array("post_id" => $id));

Upvotes: 0

Vishwas
Vishwas

Reputation: 7067

You are attempting to use a string to match a MongoId. Keep in mind that these are two different datatypes. This is there in documentation

You should query like following:

$result =  $this->likes->find(array("post_id" => new MongoId($post_id)));

As explained in doc, You can print query result by using -

foreach ($result as $doc) {
  var_dump($doc);
}

Upvotes: 1

bagrat
bagrat

Reputation: 7468

Try the following:

$result =  $this->likes->find(array("post_id" => new MongoId($post_id)));

Upvotes: 0

Related Questions