-
Notifications
You must be signed in to change notification settings - Fork 2
/
schemaTransformation.js
81 lines (77 loc) · 2.93 KB
/
schemaTransformation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* schema transformations */
/* sample documents */
db.vmessages.insert([
{ "_id" : ObjectId("5940523ba28125ddb15f15d2"), "body": {"VMESSAGE": {"072ade7d42d8" : { "messageId" : "072ade7d42d8", "create" : 1486546629585, "status" : "accept", "comment": "hi" } } }},
{ "_id" : ObjectId("5940523ba28125ddb15f15d3"), "body": {"VMESSAGE": {"595d0a56cff2" : { "messageId" : "595d0a56cff2", "create" : 1486566646197, "status" : "reject", "comment": "no good" } } }},
{ "_id" : ObjectId("5940523ba28125ddb15f15d4"), "body": {"VMESSAGE": {"52ffd09bf5b5" : { "messageId" : "52ffd09bf5b5", "create" : 1486568943752, "status" : "accept" } } }}
]);
/* desired results */
result=[
{ "_id" : ObjectId("5940523ba28125ddb15f15d2"), "message" : { "vid":"072ade7d42d8", "messageId" : "072ade7d42d8", "create" : 1486546629585, "status" : "accept", "comment": "hi" } },
{ "_id" : ObjectId("5940523ba28125ddb15f15d3"), "message" : { "vid":"595d0a56cff2", "messageId" : "595d0a56cff2", "create" : 1486566646197, "status" : "reject", "comment": "no good" } },
{ "_id" : ObjectId("5940523ba28125ddb15f15d4"), "message" : { "vid":"52ffd09bf5b5", "messageId" : "52ffd09bf5b5", "create" : 1486568943752, "status" : "accept" } }
];
/* aggregations */
/* aggregation with many addFields stages */
db.vmessages.aggregate([
{"$addFields": {
"bvm": {"$objectToArray":"$body.VMESSAGE"}
} },
{"$addFields": {
"bvm2": {"$arrayElemAt":["$bvm",0]}
} },
{"$addFields": {
"bvm": {"$objectToArray":"$bvm2.v"}
} },
{"$addFields": {
"msgarr": {
"$concatArrays": [
[ { "k":"vid", "v":"$bvm2.k"} ],
"$bvm"
]
}
} },
{"$addFields": {
"message": {"$arrayToObject": "$msgarr"}
} }
]);
/* aggregation with a single addFields or project stage */
db.vmessages.aggregate([
{"$addFields":{
"message":{
"$arrayToObject":{
"$let":{
"vars":{
"elem": {"$arrayElemAt":[
{"$objectToArray":"$body.VMESSAGE"},
0
]}
},
"in":{"$concatArrays":[
[ { k: "vid", v: "$$elem.k" } ],
{"$objectToArray": "$$elem.v"}
]}
}
}
}
}}
]);
/* aggregation with $mergeObjects instead of $concatArrays (3.6+ only) */
db.vmessages.aggregate([
{"$addFields":{
"message":{
"$let":{
"vars":{
"elem": {"$arrayElemAt":[
{"$objectToArray":"$body.VMESSAGE"},
0
]}
},
"in":{"$mergeObjects":[
{ "vid": "$$elem.k" },
"$$elem.v"
]}
}
}
}}
]);