【问题标题】:How do I find "$oid" in MongoDB instead of _id?如何在 MongoDB 中找到“$oid”而不是 _id?
【发布时间】:2022-01-17 19:01:18
【问题描述】:

我正在尝试在 MongoDB 中进行查找搜索,我只想将 objectId 作为字符串返回,但我得到了:

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

我想要:

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

这是我的查询:

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

【问题讨论】:

  • $oid 应该是MongoDB Extended JSON 的语法。如果您只是想提取 ObjectId 的“值”,您可能正在寻找 $toString
  • 您从哪里(什么工具,例如 mongo shell 等)运行查询?

标签: mongodb nosql


【解决方案1】:

这里可以测试一下(我把_id的名字设置为id)

https://mongoplayground.net/p/xdw3PpiwYId

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

【讨论】:

    【解决方案2】:

    你可以使用聚合:

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

    【讨论】:

      【解决方案3】:

      您可以申请 $toString 以获取所需格式的 id。

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

      但是您不能使用 $oid 作为字段名称,因为它是保留关键字。

      示例:https://mongoplayground.net/p/y1DsrQ-k4Hj

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-25
        • 1970-01-01
        • 1970-01-01
        • 2015-11-09
        • 1970-01-01
        • 2013-05-30
        • 2019-10-08
        相关资源
        最近更新 更多