MongoDB文档对象字段属性合并的2种转换方法
現(xiàn)在,對(duì)MongoDB中文檔對(duì)象冗余數(shù)據(jù)有中業(yè)務(wù)要求,就是對(duì)同種屬性的字段進(jìn)行合并成一個(gè)集合,效果如下圖所示:
實(shí)現(xiàn)上述數(shù)據(jù)轉(zhuǎn)換有2中方法:一種是基于NoSQL語(yǔ)言的實(shí)現(xiàn)方式,一種是基于kettle的業(yè)務(wù)數(shù)據(jù)轉(zhuǎn)換。
1、基于NoSQL語(yǔ)言的實(shí)現(xiàn)方式
首先,在MongoDB里準(zhǔn)備一個(gè)文檔數(shù)據(jù):
[mongo@mongo ~]$ mongo
MongoDB shell version: 3.2.7
connecting to: test
> show dbs
local? 0.000GB
zhul?? 0.151GB
> use datatrans
switched to db datatrans
> db.datatrans.insert({"username":"hanlingsha","gender":"girl","age":17,"TEL1":18811223298,"TEL2":18581418158,"TEL3":15286856439});
WriteResult({ "nInserted" : 1 })
> db.datatrans.findOne({"username":"hanlingsha"});
{
???????? "_id" : ObjectId("5760ad43742ee65d9552e757"),
???????? "username" : "hanlingsha",
???????? "gender" : "girl",
???????? "age" : 17,
???????? "TEL1" : 18811223298,
???????? "TEL2" : 18581418158,
???????? "TEL3" : 15286856439
}
>
???????? 使用NoSQL語(yǔ)句實(shí)現(xiàn)文檔元素合并的數(shù)據(jù)轉(zhuǎn)換:
> var hls= db.datatrans.findOne({"username":"hanlingsha"});
> hls.username=hls.username;
hanlingsha
> hls.gender=hls.gender;
girl
> hls.age=hls.age;
17
> hls.TEL=[hls.TEL1,hls.TEL2,hls.TEL3];
[ 18811223298, 18581418158, 15286856439 ]
> delete hls.TEL1;
true
> delete hls.TEL2;
true
> delete hls.TEL3;
True
> db.datatrans.update({"username":"hanlingsha"},hls);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.datatrans.findOne({"username":"hanlingsha"});
{
???????? "_id" : ObjectId("5760b2d8a1eb8f1a472e6980"),
???????? "username" : "hanlingsha",
???????? "gender" : "girl",
???????? "age" : 17,
???????? "TEL" : [
?????????????????? 18811223298,
?????????????????? 18581418158,
?????????????????? 15286856439
???????? ]
}
>
???????? 這里示例的是單個(gè)文檔的轉(zhuǎn)換,如果要轉(zhuǎn)換多個(gè)文檔,可以采用for循環(huán);下邊示例是使用kettle工具實(shí)現(xiàn)文檔屬性字段合并的數(shù)據(jù)轉(zhuǎn)換:
先使用MongoChref連接上MongoDB
現(xiàn)在,我們從datatrans集合往dataresult集合抽取數(shù)據(jù),并實(shí)現(xiàn)數(shù)據(jù)轉(zhuǎn)換:
轉(zhuǎn)換輸入連接設(shè)置
轉(zhuǎn)換輸入源設(shè)置
輸入源設(shè)置完成后可以點(diǎn)擊預(yù)覽查看要抽取的原始數(shù)據(jù)
?調(diào)整輸入源的fileds字段域設(shè)置獲取源文檔的字段域
整理編輯要選擇的字段域,刪除_id,因?yàn)檩斎氩襟E中會(huì)自動(dòng)生成_id
輸入的連接設(shè)置
輸入的數(shù)據(jù)庫(kù)及集合選擇設(shè)置
輸入前的轉(zhuǎn)換設(shè)置
點(diǎn)擊執(zhí)行轉(zhuǎn)換任務(wù)
切換到MongChref查看轉(zhuǎn)換結(jié)果:
順利完成,另外,kettle可以實(shí)現(xiàn)多文檔轉(zhuǎn)換,還能并行^_^!
總結(jié)
以上是生活随笔為你收集整理的MongoDB文档对象字段属性合并的2种转换方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA Fork Join Demo
- 下一篇: 怎么能打开AOPR的日志文件