Home > Mobile >  How do I find "$oid" in MongoDB instead of _id?
How do I find "$oid" in MongoDB instead of _id?

Time:12-15

I'm trying to do a find search in MongoDB and I just want to return the objectId as a string, but instead I get:

[
  {
    "_id": {
      "$oid": "6114ffebae76283ccfb92c44"
    }
  }
[

I want:

[
  {
    "$oid": "6114ffebae76283ccfb92c44"
  }
]

Here is my query:

db.person.find(
    { $and: [{"age":20},{"name":"Frank"}] }, {"_id":1}
)

CodePudding user response:

You could apply a $toString to get the id in your desired format.

db.collection.find({},
{
  "_id": {
    $toString: "$_id"
  }
})

However you can't use the $oid as field name because is a reserved keyword.

Example: https://mongoplayground.net/p/y1DsrQ-k4Hj

CodePudding user response:

You can use aggregate:

db.collection.aggregate([
  {
    $project: {
      _id: {
        $toString: "$_id"
      }
    }
  }
])

CodePudding user response:

Here you can test it (I set the name of _id to id)

https://mongoplayground.net/p/xdw3PpiwYId

db.person.find({
  $and: [
    {
      "age": 20
    },
    {
      "name": "Frank"
    }
  ]
},
{
  "id": {
    $toString: "$_id"
  },
  "_id": 0
})
  • Related