有一个包含数据的集合
date_new:Array
使用mongodb聚合如何将其转换为这样的字符串,如果有空字符串,则将其转换为" "
date_new:Array
0: " "
答案 0 :(得分:1)
请尝试:
db.yourCollectionName.aggregate([{
$addFields:
{
date_new: {
$arrayToObject:
{
$map:
{
input: "$date_new",
as: "each",
in: [{ $toString: { $indexOfArray: ["$date_new", '$$each'] } }, '$$each']
}
}
}
}
}])
收集数据:
/* 1 */
{
"_id" : ObjectId("5e1e2a74d3c98f2a7100fd44"),
"date_new" : [
"abc",
"def",
""
]
}
/* 2 */
{
"_id" : ObjectId("5e1e2f25d3c98f2a7100fd45"),
"date_new" : []
}
结果:
/* 1 */
{
"_id" : ObjectId("5e1e2a74d3c98f2a7100fd44"),
"date_new" : {
"0" : "abc",
"1" : "def",
"2" : ""
}
}
/* 2 */
{
"_id" : ObjectId("5e1e2f25d3c98f2a7100fd45"),
"date_new" : {}
}