需要从Mongo获取特定的字段,DB是巨大的,所以我更喜欢以正确的格式获取值,而不是对其进行后处理。
例如,有两个字段需要转换格式:
1_id: ObjectId(‘604e0dbc96a93a45bfc5b0’)改为“604edbc96a0c93a45bfc0b0:2.生日: 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')
}检索Jsons特定字段:
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中有上百万个记录时,我的最佳选择是什么?
发布于 2021-03-23 10:11:16
演示- 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
}
}
])https://stackoverflow.com/questions/66760980
复制相似问题