venkat
venkat

Reputation: 69

Mongodb return objectId as string

db.getCollection('User').find({
    "userId" : ObjectId("5a141ac4048378xb52c3e5a9"),
        "userRole" : "ADMIN",
        "Id" : "1234567890"})

    result:
    {
        "userId" : ObjectId("5a141ac4048378xb52c3e5a9"),
        "userRole" : "ADMIN",
        "Id" : "1234567890"
    }

    Expecting output:
    {
        "userId" : "5a141ac4048378xb52c3e5a9",
        "userRole" : "ADMIN",
        "Id" : "1234567890"
    }

I am very new to mongodb i nedded to return objectId as String ,i neeed some suggestion to do that.

Upvotes: 0

Views: 3950

Answers (2)

Clement Amarnath
Clement Amarnath

Reputation: 5476

It can be done simply using the below approach

db.User.find({"userId": objectId("5a141ac4048378ab52c3e5a9")}).map(
      function(doc) { 
         return { "userId": doc.userId.str}
      });

Please see ObjectId for more methods

Upvotes: 2

keyst0rke
keyst0rke

Reputation: 16

You can try use a aggregation But ObjectId isn't strings, it's just numbers, why you want present it as string?

Upvotes: 0

Related Questions