J
J
Julia Kovalenko2016-06-21 18:56:38
Yii
Julia Kovalenko, 2016-06-21 18:56:38

How to search in MongoDB in php by _id?

There is a collection 'test' in mongo

...
{ "_id" : NumberLong("6763623186861095307"), "first_name" : "Людмила"}
{ "_id" : 10991155627267640000, "first_name" : "Нина"}
{ "_id" : 12946078521768528000, "first_name" : "александр" }
{ "_id" : NumberLong("6755764668161210064"), "first_name" : "Alexandr" }
{ "_id" : 12681288148839543000, "first_name" : "Анатолий"}
...

You need to search by _id.
I'm looking for yii2
$query = new MongoQuery;
$id = "6763623186861095307";
$query->select(['_id', 'first_name'])
           ->from('test')
           ->where(['_id' => (int)$id])
           ->limit(1);
$result = $query->one();

But $result == false.
This code worked before.
How to do it now? Maybe without yii2, in pure php?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Julia Kovalenko, 2016-06-22
@kovalenko_jul_s

In general, along the way, with the next update of the mongo driver for php, an interesting bug popped up.
As a result, the design works

...
->where(['_id' => (int)$id])
->orWhere(['_id' => (float)$id])

Works with both NumberLong and regular Int.

A
Alex Japson, 2016-06-21
@bonuce

You pass _id as a string, monga accepts ObjectId
Here below is an example of how to cast to objectId
And here is another link
And judging by the monga code in your question, do you add _id to the object yourself? When you create an entry in monge, it itself puts down the _id for each element in the collection.
Mongo entries should be like this

{ "_id" : ObjectId("6763623186861095307"), "first_name" : "Людмила"}
{ "_id" : ObjectId("10991155627267640000"), "first_name" : "Нина"}
{ "_id" : ObjectId("12946078521768528000"), "first_name" : "александр" }
{ "_id" : ObjectId("6755764668161210064"), "first_name" : "Alexandr" }
{ "_id" : ObjectId("12681288148839543000"), "first_name" : "Анатолий"}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question