4

I am trying to get the _id from a collection without getting the ObjectId part.

When I try and query it this way:

db.collection.aggregate([
    {'$unwind': '$_id'}, 
    {
        '$project': {
            '_id': '$_id'
        }
    }
])

This returns:

ObjectId("51234yhf789")
ObjectId("51234dff779")
ObjectId("51234yhf745")
ObjectId("51234dff123")
ObjectId("51234d45123")

Even when I try: '_id': '$_id'.valueOf(), I get the same thing.

How do I get:

51234yhf789
51234dff779
51234yhf745
51234dff123
51234d45123

Need help for MongoDB V3.6 and below

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
nb_nb_nb
  • 1,243
  • 11
  • 36

1 Answers1

4

On MongoDB version > 4.0 you can use $toString to convert ObjectId() to string :

db.collection.aggregate([
    {'$unwind': '$_id'}, 
    {
        '$project': {
            '_id': {$toString : '$_id' }
        }
    }
])
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • Sorry, I should've mentioned this. Its for MongoDB 3.6 – nb_nb_nb Apr 27 '20 at 16:20
  • @noob : I don't think you can do that below `4.0`, Also why are you looking for string ? Are you doing anything further with query ? Cause if you just returning from there, then driver in code should automatically convert it to type of string as `ObjectId()` is not of any type related to `JSON`.. – whoami - fakeFaceTrueSoul Apr 27 '20 at 16:23
  • I am trying to join a string with the objectId – nb_nb_nb Apr 27 '20 at 16:25
  • If you would post the query you'd actually like to run, we can help with that directly, see [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Joe Apr 27 '20 at 16:42