1

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?

2 Answers 2

1

_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)])
Sign up to request clarification or add additional context in comments.

1 Comment

So simple, so correct.. I feel so stupid now :) thanks! I'll accept your answer since you also included the ObjectID class.
1

$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 ])

1 Comment

Thanks this worked flawlessly, but seeing as the other person was 2 minutes faster with a pretty much the same answer I'd give the accepted to him, but both will get my upvotes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.