[英]Python [mongo] - convert return fields of find()
need to get specific fields from Mongo, The DB is huge so I prefer getting the values in right format and not post processing it.需要从 Mongo 获取特定字段,数据库很大,所以我更喜欢以正确的格式获取值,而不是对其进行后处理。
in example, There are 2 fields which need to convert the format:例如,有 2 个字段需要转换格式:
1_id: ObjectId('604e0dbc96a0c93a45bfc5b0') to string as "604e0dbc96a0c93a45bfc5b0: 2.birthdate: ISODate('1999-11-10T00:00:00.000Z') - to string in date format "10/11/1999". 1_id: ObjectId('604e0dbc96a0c93a45bfc5b0') 字符串为“604e0dbc96a0c93a45bfc5b0: 2.birthdate: ISODate('1999-11-10T00:00:00.000Z') - 字符串日期格式为“10/11/1999”。
Example of json in MongoDB: MongoDB 中的 json 示例:
{
_id: ObjectId('604e0dbc96a0c93a45bfc5b0'),
address: 'BOB addrees',
name: 'BOB',
last_name: 'Habanero',
birthdate: ISODate('1000-11-10T00:00:00.000Z')
}
retrieving the Jsons specific fields:检索 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} )
Is there an option to use convert functions for returning values in find()?是否可以选择使用转换函数在 find() 中返回值? case not, what are my best option to do it while i have several fields required to format the values and there are MILLION of records in the MongoDB?
如果不是,当我需要几个字段来格式化值并且 MongoDB 中有数百万条记录时,我最好的选择是什么?
Demo - https://mongoplayground.net/p/4OcF0O74PvU演示 - https://mongoplayground.net/p/4OcF0O74PvU
You've to use an aggregation query to do that.您必须使用聚合查询来做到这一点。
convert object to string using $toString使用$toString将 object 转换为字符串
Use $dateToString to format your date使用$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
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.