Alps
Alps

Reputation: 31

How to search document using ObjectId in MongoDB (Anypoint Studio)

I'm using AnypointStudio to create an API and I'm trying to search for a document using the ObjectId on MongoDB but I can't make it work. I have tried searching with the use of other fields in the collection and it works just fine. Here is the value of the Find query I am currently using.

output application/json
---
{   
    "_id" : "5c088f4264c73358f4f7e3c0"
}

Here's an example result I have upon searching with the use of the uid field.

{
    "_id": {
        "$oid": "5c088f4264c73357f4f7e3c0"
    },
    "uid": "test",
    "name": "test",
    "validUser": true,
    "oauth_client_id": "55628a5730ad44719e63b34c36604401",
    "customer": "test customer"
}

Can anyone please help me to search document using the ObjectId? Thanks

Upvotes: 0

Views: 613

Answers (2)

Alps
Alps

Reputation: 31

I finally got the answer with some experimentations. I noticed the structure of the _id field and tried using this in the query "_id" : {"$oid" : "5c088f4264c73358f4f7e3c0"} but won't work since $ symbol is a reference symbol(?). So I tried using \ before the $ and it works.

output application/json
---
{
    "_id" : {"\$oid" : "5c088f4264c73358f4f7e3c0"}
}

Upvotes: 2

Shmili Breuer
Shmili Breuer

Reputation: 4147

The example you show should work, you may need to wrap it like this

{   
    _id : ObjectId("5c088f4264c73358f4f7e3c0") 
}

Hope this helps

Upvotes: -1

Related Questions