Reputation: 164
I have a collection "A" that have documents:
{_id:1, a1: "degree"}
{_id:2, a2: "score"} ...
I need to transform that collection to key-value structure such as:
{_id: x, {name: "a1", label: "degree"} }
{_id: y, {name: "a2", label: "score"} }
Problem is every document can have different field name in collection A.
To get the field name, I can use javascript as follows,
But still can't find way to get each field value without knowing field name.
var arr = new Array()
var x = 0
var cur = db."A".find()
while( cur.hasNext() ) {
var i = 0
for( var field in cur[x] ) {
arr[i] = field; // get field name
i++;}
db."B".save( { "name": arr[1], //fieldname
"label": //how to put value without knowing field name?
)
x++;
}
Do you have any idea how to get field value without knowing the name?
thank you.
Upvotes: 1
Views: 735
Reputation: 164
Thanks for comments and answers! I have completed my javascript code as follows:
var arr = new Array()
var x = 0
var cur = db.A.find()
while( cur.hasNext() ) {
var i = 0
for( var field in cur[x] ) {
arr[i] = field; // get field name
print( "field name="+ field);
print( "the value="+cur[x][field] );
i++;
}
x++;
}
Upvotes: 1
Reputation: 1528
I'm not sure is this what you really want but hope this help.
Try this :
var obj = [
{_id: x, {name: "a1", label: "degree"} },
{_id: y, {name: "a2", label: "score"} }
];
for (index in obj) {
for (key in obj[index]) {
console.log(key);
console.log(obj[index][key]);
}
}
Upvotes: 2