MongoDB-将具有数组的一个记录转换为新集合中的多个记录

时间:2018-10-09 17:23:54

标签: python mongodb

[MongoDB shell或pyMongo] ,我想知道如何有效地将一个字段中具有数组的集合中的一个记录转换为一个新集合中的多个记录。到目前为止,我能够实现的唯一解决方案是逐个迭代记录,然后迭代我想要的字段中的数组并进行单个插入。我希望有一种更有效的方法。

示例:

我想在MongoDB中收集一个结构类似于:

[{
    "_id": 1,
    "points": ["a", "b", "c"]
}, {
    "_id": 2,
    "points": ["d"]
}]

并将其转换为如下形式:

[{
    "_id": 1,
    "points": "a"
}, {
    "_id": 2,
    "points": "b"
}, {
    "_id": 3,
    "points": "c"
}, {
    "_id": 4,
    "points": "d"
}]

2 个答案:

答案 0 :(得分:0)

假设您对新集合中自动生成的_id值没问题,则可以通过使用$unwind展开points数组和{{ 1}},将结果输出到新集合:

$out

答案 1 :(得分:0)

这是另一个版本,由于第二个$unwind和可能很大的$group,其性能可能会比@JohnnyHK的解决方案差,但它会根据您可以在$sort阶段:

db.collection.aggregate([{
    // flatten the "points" array to get individual documents
    $unwind: { "path": "$points" },
}, {
    // sort by some criterion
    $sort: { "points": 1 }
}, {
    // throw all sorted "points" in the very same massive array
    $group: {
        _id: null,
        "points": { $push: "$points" },
    }
}, {
    // flatten the massive array making each document's position index its `_id` field
    $unwind: {
        "path": "$points",
        includeArrayIndex: "_id"
    }
} , {
    // write results to new "result" collection
    $out: "result"
}], {
    // make sure we do not run into memory issues
    allowDiskUse: true
})