How to convert a string to a mongodb ObjectId?

Viewed 5699

I am successfully able to insert the following in mongo db as a string. But I want it to be inserted as an objectId.

parentId": "5ced2388dbbbe124d8671067"

This is the parentId in string format.

How can I convert it to objectId format?

6 Answers

Mongodb 4.0 has introduced $toObjectId aggregation to convert string value to an ObjectId. here's an example

db.getCollection('foo_collection').aggregate([
  { "$addFields": {
    "bar" :  { "$toObjectId": "$bar_id" }
  }},
  { "$out": "new_foo_collection" }
])

Here's the link

you must use mongoose like that

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('5ced2388dbbbe124d8671067');

You can use mongoose:

const mongoose = require('mongoose');
let yourId = mongoose.Types.ObjectId('5ced2388dbbbe124d8671067');

It will return type ObjectId variable .

in case of typescript:

import mongoose from "mongoose"; // will work
import * as mongoose from "mongoose"; // won't work

then

const objectId = mongoose.Types.ObjectId(id);

Happy Coding.

const ObjectId = require('mongodb').ObjectID
parentId =  "5ced2388dbbbe124d8671067"
let data = new ObjectId(parentId)
console.log(typeof(data))
console.log(typeof(parentId))

It can be done by writing two lines of code to save it as a object id

let ObjectId = require('mongodb').ObjectID;
parentID = ObjectId("5ced2388dbbbe124d8671067")
Related