0

需要从 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 中有数百万条记录时,我最好的选择是什么?

4

1 回答 1

3

演示 - 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
    }
  }
])
于 2021-03-23T10:11:16.240 回答