1

I am working with MongoDB 3.6. I'm trying to do an aggregation $lookup as below.

$lookup

{
  from: 'm_mtr',
  localField: 'mtdid',
  foreignField: '_id',
  as: 'mm'
}

This doesn't work for me as 'mtdid' is a string with values like '5bdbe5bcff10z046fcf8f04a'and '_id' is an Object Id field with values like 'ObjectId('5bdbe5bcff10z046fcf8f04a')'.

Is there a way to convert string to ObjectId? I know this is possible in Mongodb 4.0. Unfortunately I don't have an option of using anything other than 3.6.

ROOT
  • 11,363
  • 5
  • 30
  • 45
Shiny S U
  • 43
  • 2
  • 5
  • Possible duplicate of [how to $project ObjectId to string value in mongodb aggregate?](https://stackoverflow.com/questions/36059986/how-to-project-objectid-to-string-value-in-mongodb-aggregate) – Ashh Dec 28 '18 at 05:12
  • Try this one https://stackoverflow.com/questions/33891511/mongodb-concat-int-and-string – Ashwanth Madhav Feb 01 '19 at 12:19

1 Answers1

0

In mongoose, you can use this function:

let id = new mongoose.Types.ObjectId('5bdbe5bcff10z046fcf8f04a');
Cong Nguyen
  • 3,199
  • 1
  • 23
  • 22
  • Thanks! can ObjectId take a string variable as the parameter? – Shiny S U Dec 29 '18 at 00:44
  • No. you need to convert string to ObjectId first. // Get the objectID type var ObjectID = require('mongodb').ObjectID; var idString = '5bdbe5bcff10z046fcf8f04a'; collection.findOne({_id: new ObjectID(idString)}, console.log) // ok collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined – Cong Nguyen Dec 29 '18 at 02:41