killstreet
killstreet

Reputation: 1332

mongodb query search inside array PHP

I'm trying to query on a specific key in a mongodb, however I keep ending up with empty results while it should be returning 1 record. I have looked at different questions which are basically the same but their answers haven't helped me.

I got the following structure in my mongo for example

{
    "_id": {
        "$oid": "5bb7388354f02b041b6819b2"
    },
    "raw": {
        "etag": "W/\"CQAAABYADtqt1sMfi5R4onmiTyvUAALqHFp9\"",
        "id": "abcdefg"
    }
}

I currently have tried the following query:

$id = "5bb7388354f02b041b6819b2";
$this->collection->find(['_id' => ['$oid' => $id]]);

However this returns an error

unknown operator: $oid

Now whatever I try, it either returns "unknown operator" or it returns nothing. I also tried switching the query and using the ID inside raw as follow.

$id = "abcdefg";
$this->collection->find(['raw' => ['id' => $id]]);

but this returns nothing for me. So I was wondering, what it is i'm doing wrong?

Upvotes: 1

Views: 39

Answers (2)

Ashh
Ashh

Reputation: 46451

$oid is not the field. It is just a denotation that it's an mongodb ObjectId

So you can simply try this

$this->collection->find([ '_id' => $id ])

or

$this->collection->find([ 'raw.id' => $id ])

Upvotes: 1

msbytes
msbytes

Reputation: 26

_id in MongoDB is not a string but ObjectId so you have to pass it right to query

$this->collection->find(['_id' => new MongoDB\BSON\ObjectID($id)])

Upvotes: 1

Related Questions