How to convert datatype from string to ObjectId

3,042 views
Skip to first unread message

sarath te

unread,
Sep 12, 2017, 6:25:33 PM9/12/17
to mongodb-user
I have "booking" collection it has 24000 entries. In this collection I have field "user". At-present it's data type is string. I am trying to convert data type from string to ObjectId. But I am getting error "invalid object id".

db.booking.find({user: {$exists:true}}).forEach( function(x) {
... var id = new ObjectId(x.user);
... db.booking.update({_id: x._id},
... {$set: {user: id }});
... });
2017-09-12T11:28:28.701+0000 E QUERY    [thread1] Error: invalid object id: length :
@(shell):2:10
DBQuery.prototype.forEach@src/mongo/shell/query.js:501:1
@(shell):1:1

To avoid error "invalid object id: length". I have added try catch method but getting another error "SyntaxError: missing ) after catch". 

> db.booking.find({user: {$exists:true}}).forEach( function(x) {
...      var id = new ObjectId(x.user);
...      try {
...          id = new MongoId(id);
...      }
...      catch (MongoException $ex) {
...         id = new MongoId();
...      }
...      db.booking.update({_id: x._id}, {$set: {user: id }});
... });
2017-09-12T11:38:35.009+0000 E QUERY    [thread1] SyntaxError: missing ) after catch @(shell):6:27


Booking Collection

    { "_id" : ObjectId("58046a49f8f888a80b00002a"), "cabinname" : "Matras-Haus", "checkin_from" : ISODate("2016-10-17T00:00:00Z"), "reserve_to" : ISODate("2016-10-20T00:00:00Z"), "user" : "57877d23049ac1b819000029", "beds" : "2", "dormitory" : "1", "sleeps" : "3", "clubmember" : "1", "status" : "4", "comments" : "", "bookingdate" : ISODate("2016-10-17T06:06:01Z"), "reservation_cancel" : "2", "is_delete" : NumberLong(1), "payment_status" : "1" }
    { "_id" : ObjectId("58183678d2ae67a404431d5c"), "cabinname" : "Kemptner Hütte", "checkin_from" : ISODate("2016-10-31T23:00:00Z"), "reserve_to" : ISODate("2016-11-23T23:00:00Z"), "user" : "57877d23049ac1b819000029", "beds" : "2", "dormitory" : "0", "sleeps" : "2", "clubmember" : "0", "status" : "1", "total_price" : "1288", "payon_cabin" : "1288", "bed_prefer" : "0", "guests" : "2", "comments" : "", "prepayment_amount" : "0", "bookingdate" : ISODate("2016-11-01T06:30:16Z"), "reservation_cancel" : "2", "is_delete" : NumberLong(1), "payment_status" : "0" }
    { "_id" : ObjectId("581b31f3d2ae674d5f431d5b"), "cabinname" : "Kemptner Hütte", "checkin_from" : ISODate("2016-11-07T23:00:00Z"), "reserve_to" : ISODate("2016-11-17T23:00:00Z"), "user" : "", "beds" : "3", "dormitory" : "0", "sleeps" : "3", "clubmember" : "0", "status" : "1", "total_price" : "840", "payon_cabin" : "840", "bed_prefer" : "0", "guests" : "3", "comments" : "", "prepayment_amount" : "0", "bookingdate" : ISODate("2016-11-03T12:47:47Z"), "reservation_cancel" : "2", "is_delete" : NumberLong(1) }
    { "_id" : ObjectId("5821af65d2ae67c82154efc5"), "cabinname" : "Kemptner Hütte", "checkin_from" : ISODate("2017-09-05T22:00:00Z"), "reserve_to" : ISODate("2018-01-24T23:00:00Z"), "user" : "57877d23049ac1b819000029", "sleeps" : "2", "clubmember" : "0", "status" : "1", "total_price" : "5640", "payon_cabin" : "5630", "bed_prefer" : "0", "guests" : "2", "comments" : "", "prepayment_amount" : "21.25", "bookingdate" : ISODate("2016-11-08T10:56:37Z"), "reservation_cancel" : "2", "is_delete" : NumberLong(1) }
    { "_id" : ObjectId("582558d4d2ae679c4d8b4567"), "cabinname" : "2", "checkin_from" : ISODate("2017-07-31T22:00:00Z"), "reserve_to" : ISODate("2017-08-02T22:00:00Z"), "user" : "57877d23049ac1b819000029", "beds" : "", "dormitory" : "", "sleeps" : "2", "clubmember" : "0", "status" : "", "total_price" : "80", "payon_cabin" : "60", "halfboard" : "", "bed_prefer" : "0", "guests" : "2", "prepayment_amount" : "20", "bookingdate" : ISODate("2016-11-11T05:36:20Z"), "is_delete" : NumberLong(1) }
    { "_id" : ObjectId("58352c3cd2ae672341ec89e1"), "cabinname" : "Kemptner Hütte", "checkin_from" : ISODate("2017-05-31T22:00:00Z"), "reserve_to" : ISODate("2017-06-02T22:00:00Z"), "user" : "", "beds" : "", "dormitory" : "", "sleeps" : "2", "clubmember" : "0", "status" : "", "total_price" : "80", "payon_cabin" : "60", "halfboard" : "", "bed_prefer" : "0", "guests" : "2", "prepayment_amount" : "20", "bookingdate" : ISODate("2016-11-23T05:42:20Z"), "reservation_cancel" : "2", "is_delete" : NumberLong(1) }

OmIndia Tech India

unread,
Sep 15, 2017, 6:22:24 AM9/15/17
to mongodb-user

ObjectId mongodbid = ObjectId.Parse(your string Value);


But i also your need help .

i want to access my secure mongodb database .from asp.net page using C# 

String uri = "mongodb://admin:password@localhost:27017/admin";

        var client = new MongoClient(uri);
        MongoServer _Server = client.GetServer();
        var db = _Server.GetDatabase("AshaSoft");
        var col = db.GetCollection<BsonDocument>("AshaFileType");
        Response.Write(col.FindOne(Query.EQ("_id", "59b1140e9b08cb45102eeb97")));

i am using this code but this coding showing this error 


Wan Bachtiar

unread,
Sep 19, 2017, 3:22:52 AM9/19/17
to mongodb-user

But I am getting error “invalid object id”.

Hi Sarath,

This is because you’re trying to initialise ObjectId() with an empty string.
Your filter of {user: {$exists:true}} is capturing documents where field user exist, but not where field user exist with an empty string. i.e. your document example "_id" : ObjectId("581b31f3d2ae674d5f431d5b").

Depending on what your use case is, you could try for both cases, where user field exists and value is not equal to empty string. i.e. {"user":{"$exists":true, "$ne": ""}}

I have added try catch method but getting another error “SyntaxError: missing ) after catch”.

You can try to put in the try/catch block the line var id = new ObjectId(x.user); , because this line is throwing the exception.
As an example:

db.booking.find({"user":{"$exists":true}}).forEach(function(x){ 
    let id;
    try {     
        id = new ObjectId(x.user);  
    } 
    catch (err) {     
        id = new ObjectId();  
    } 
    db.booking.update( { "_id": x._id }, { $set: { user:id } } );  
    }
);

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages