0

I have mongoId like this :

ObjectId("53056c1e211b6f2e5d8b4567")

I only want

"53056c1e211b6f2e5d8b4567"

I tried toString but it returns the whole thing as string.
I know I can extract using string operations, but is there a native way to do so ?

Not a bug
  • 4,286
  • 2
  • 40
  • 80
Aysennoussi
  • 3,720
  • 3
  • 36
  • 60
  • Why do you want only "53056c1e211b6f2e5d8b4567"? What is your use case? – Lalit Agarwal May 09 '14 at 10:01
  • I have users and posts collections . I want to find posts by users so I grab the id of a user and it fills the author field in posts. – Aysennoussi May 09 '14 at 10:02
  • You could even query it by ObjectId. As far as I know all the MongoDB drivers support querying using object id. In java you could so something like http://stackoverflow.com/questions/9797935/how-to-query-documents-using-id-field-in-java-mongodb-driver – Lalit Agarwal May 09 '14 at 10:14
  • I don't fully understand your sayings.. author is a string field that has the value of and id object of an other collection. it is not stored as objectid but as string .. nevertheless , I got my answer , thanks :) – Aysennoussi May 09 '14 at 10:17
  • Oh!! My bad.. I thought that it was saved as object id in your posts collection. – Lalit Agarwal May 09 '14 at 10:24

1 Answers1

2

You can do it:

ObjectId("53056c1e211b6f2e5d8b4567").valueOf()

it have to return the following string:

53056c1e211b6f2e5d8b4567

For more details, see docs

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
jmen7070
  • 606
  • 5
  • 9