【monogo aggregate $set 将嵌套字典中的键值对取出放到外层】

由于一些原因,导致产生如下数据结构的数据:

{ 
    "_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 基础上增加字段的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值