【问题标题】:Python [mongo] - convert return fields of find()Python [mongo] - 转换 find() 的返回字段
【发布时间】:2021-03-23 10:02:32
【问题描述】:

需要从Mongo获取特定字段, 数据库很大,所以我更喜欢以正确的格式获取值 不进行后期处理。

例如, 有2个字段需要转换格式:

1_id: ObjectId('604e0dbc96a0c93a45bfc5b0') 字符串为“604e0dbc96a0c93a45bfc5b0: 2.birthdate: ISODate('1999-11-10T00:00:00.000Z') - 以日期格式“10/11/1999”的字符串。

MongoDB中的json示例:

{
    _id: ObjectId('604e0dbc96a0c93a45bfc5b0'),
    address: 'BOB addrees',
    name: 'BOB',
    last_name: 'Habanero',
    birthdate: ISODate('1000-11-10T00:00:00.000Z')
}

检索 Json 特定字段:

customers_cursor =  DB.customer.find({},{"_id": 1,"name" :1 ,"last_name":1 ,"customer_type":1,"address.0":1 ,"email":1 ,"birthdate" :1 ,"customer_status":1} )

是否可以选择使用转换函数在 find() 中返回值? 如果不是,当我需要几个字段来格式化值并且 MongoDB 中有数百万条记录时,我最好的选择是什么?

【问题讨论】:

  • 是否要将 ISODtae 转换为日期时间 dtring 格式和字符串中的 ObjectId?

标签: python mongodb mongodb-query aggregation-framework motorengine


【解决方案1】:

演示 - https://mongoplayground.net/p/4OcF0O74PvU

您必须使用聚合查询来做到这一点。

使用$toString将对象转换为字符串

使用$dateToString 格式化您的日期

db.collection.aggregate([
  {
    "$project": {
      "_id": {
        "$toString": "$_id"
      },
      "name": 1,
      "last_name": 1,
      "customer_type": 1,
      "address.0": 1,
      "email": 1,
      "birthdate": {
        "$dateToString": {
          "format": "%d/%m/%Y",
          "date": "$birthdate"
        }
      },
      "customer_status": 1
    }
  }
])

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 2016-03-03
    • 2020-04-15
    • 2019-07-28
    • 2020-10-19
    • 2019-01-14
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多