Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get _id without ObjectId from MongoDB

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

like image 910
nb_nb_nb Avatar asked Oct 16 '25 04:10

nb_nb_nb


1 Answers

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

db.collection.aggregate([
    {'$unwind': '$_id'}, 
    {
        '$project': {
            '_id': {$toString : '$_id' }
        }
    }
])
like image 106
whoami - fakeFaceTrueSoul Avatar answered Oct 17 '25 21:10

whoami - fakeFaceTrueSoul