-1

I have the following document in MongoDB.

{
    "_id" : ObjectId("5d5f9a3056be496aec564bca"),
    "field1" : "value1",
    "field2" : "value2",
}

How can I query this and get the ObjectId as String. like below

{
    "_id" : "5d5f9a3056be496aec564bca",
    "field1" : "value1",
    "field2" : "value2",
}

2 Answers 2

1

You can use $toString operator to do this task.

db.collection.aggregate([
  {
    $project: {
      _id: {
        $toString: "$_id",

      },
      field1: 1,
      field2: 1
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry forgot to mention. DB version is 3.6.18
1

On MongoDB version >= 4.0 - You'll have an option to convert the type of the field, Here you can use $toString to convert it to string :

db.collection.aggregate([
  /** `$addFields` will overwrite the existing value of field if a field exists with same name,
   *   if not will create a new additional field on doc */
  {
    $addFields: {
      _id: {
        $toString: "$_id"
      }
    }
  }
])

Test : mongoplayground

Note : On version below 4.0 there is no way to convert ObjectId() to string using MongoDB query unless you use any code to do it.

8 Comments

Sorry forgot to mention. DB version is 3.6.18
@ShamnadPS : So as I said there is no way to convert ObjectId() to String in query for version prior to 4.0 but when you read results in code as ObjectId() is not a supported type of JSON it will by default be converted to string !! But converting in query is not possible..
Could you please share a reference of how to do that please.
Right now I read it as a document and convert to my Object in which Id is of type String and I get data conversation error saying ObjectID cannot be type cast to String
@ShamnadPS : What are you trying to do ? Are you trying to read docs and convert ObjectId() to String in code ?
|

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.