由于一些原因,导致产生如下数据结构的数据:
{
"_id" : {
"code" : "123456789123456789",
"name" : "xxxxxx贸易有限公司"
}
}
{
"_id" : {
"code" : "987654321987654321",
"name" : "yyyyyy信息科技有限公司"
}
}
....
这种数据格式是不符合使用需求的,需要处理成下面的结构:
{
"_id" : ObjectId(6...............)
"code" : "123456789123456789",
"name" : "xxxxxx贸易有限公司"
}
{
"_id" : ObjectId(6...............)
"code" : "987654321987654321",
"name" : "yyyyyy信息科技有限公司"
}
....
可以使用 MongoDB 自己的 Aggregate 相关语法进行处理
use dbname;
db.getCollection("collection").aggregate(
[
{
"$set" : {
"name" : "$_id.name",
"code" : "$_id.code"
}
},
{
"$project" : {
"name" : 1.0,
"code" : 1.0,
"_id" : 0.0
}
}
],
// 当查询需要 16M 以上内存时需要将 allowDiskUse 置为 true
{
"allowDiskUse" : false
}
);
将上述查询结果通过 Studio3T 直接导出到新表中,目标达成。
小结
关于 MongoDB Aggregate 语法关键词 $set 的用法,官方文档 如下:
Adds new fields to documents. $set outputs documents that contain all existing fields from the input documents and newly added fields.
The $set stage is an alias for $addFields.
Both stages are equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.
$set has the following form:
{ $set: { <newField>: <expression>, ... } }
大意就是说 $set 是 $addFields 的别名,在原始 document 基础上增加字段的。