我目前正在修改架构,我需要使用聚合框架和 bulkWrite
进行相对简单的转换。 .
我希望能够获取这个数组:
{
...,
"images" : [
"http://example.com/...",
"http://example.com/...",
"http://example.com/..."
]
}
并聚合到一个类似的数组,其中封装了原始值:
{
...,
"images" : [
{url: "http://example.com/..."},
{url: "http://example.com/..."},
{url: "http://example.com/..."}
]
}
这个慢查询可以工作,但展开整个集合的成本却高得离谱。
[
{
$match: {}
},
{
$unwind: {
path : "$images",
}
},
{
$group: {
_id: "$_id",
images_2: {$addToSet: {url: "$images"}}
}
},
]
如何通过project
或其他一些更便宜的聚合来实现这一点?
最佳答案
$map表达式应该可以完成这项工作,试试这个:
db.col.aggregate([
{
$project: {
images: {
$map: {
input: '$images',
as: 'url',
in: {
url: '$$url'
}
}
}
}
}
]);
关于mongodb - 将数组封装/转换为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41658785/