skip to Main Content

I have an aggregation query whose MongoDB repsonse is :

_id: ObjectId('5e822d6c87502b3a9b751786')

I would like to get the string inside the ObjectId which is 5e822d6c87502b3a9b751786.


[ Problem ]

I have searched this question but so far there are only three operators that are capable to do this, namely $toString, $toObjectId, and $convert :

$project: {
      _id: {
        $toString: "$_id"
      }
}
$project: {
      _id: {
        $toObjectId: "$_id"
      }
}
$project: {
      _id: {
        $convert: {
          input: "$_id"
          to: "string"
        }
      }
}

MongoDB v3.6 does not support them if I am not mistaken.
Is there any workaround in MongoDB v3.6 to get a string inside an ObjectId?

Any help is much appreciated 🙂

2

Answers


  1. Chosen as BEST ANSWER

    Just want to add ray's answer after some findings.

    Having defined a model in the app, here are some workaround that worked for me:

    1. Promises
    const TestCollection = require('../models/testCollection');
    
    function getStringInObjectId() {
      TestCollection.find().then(t => {
        t.forEach(doc => {
          // Put some logic here...
          console.log('string in ObjectId :', JSON.stringify(doc._id));
        });
      });
    }
    
    1. Async/Await
    const TestCollection = require('../models/testCollection');
    
    async function getStringInObjectId() {
      const t = await TestCollection.find();
      t.forEach(doc => {
        // Put some logic here...
        console.log('string in ObjectId :', JSON.stringify(doc._id));
      });
    }
    

    Same goes to aggregation :

    1. Promises
    const TestCollection = require('../models/testCollection');
    
    function getStringInObjectId() {
      TestCollection.aggregate([
        { $match: { 'name': 'marc' } }, // <- { 'name': 'marc' } is just an example, feel free to change it
        // Put some stages here if required...
      ]).then(t => {
        console.log('string in ObjectId : ', t[0]._id.toString());
      });
    }
    
    1. Async/Await
    const TestCollection = require('../models/testCollection');
    
    async function getStringInObjectId() {
      const t = await TestCollection.aggregate([
        { $match: { 'name': 'marc' } }, // <- { 'name': 'marc' } is just an example, feel free to change it
        // Put some stages here if required...
      ]);
      console.log('string in ObjectId : ', t[0]._id.toString());
    }
    

    Either JSON.stringify() or toString() can be used to convert it to string. Feel free to correct variable names.


  2. For MongoDB v3.6, as $toString and $convert is not available until v4.0, you may need to resort to JS/application-level access to the _id.

    db.testCollection.insertMany([
    {
        "_id": ObjectId("5e822d6c87502b3a9b751786")
    }]);
    
    db.testCollection.find().forEach( doc => { 
        // put your logic for process here
        console.log(JSON.stringify(doc._id))
    });
    

    output:

    "5e822d6c87502b3a9b751786"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search