M. Gara
M. Gara

Reputation: 1078

Convert string to objectid mongodb

I have a collection of 800 ish documents, I would like to create a new one from this collection by adding a new field which is based on another field as follows:

Basically my foo_collection documents contains a field that has been set as a string however I want to convert it to a new one by "casting" it's value to a mongoose Id:

I tried this so far but I get the error : Invalid onjectId: Length

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

the expected result is a new collection with documents that has 1 more field "bar" with the value an ObjectId()

Thanks for your help !

Upvotes: 2

Views: 3611

Answers (1)

Ashh
Ashh

Reputation: 46441

Mongodb 4.0 has introduced $toObjectId aggregation to convert string value to an ObjectId... So you can use this

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

Upvotes: 3

Related Questions