[英]Mongodb: how to read value without knowing field name?
I have a collection "A" that have documents: 我有一个包含文件的集合“ A”:
{_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, 问题是每个文档在集合A中可以有不同的字段名称。要获取字段名称,我可以使用javascript,如下所示:
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. 谢谢。
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]);
}
}
Thanks for comments and answers! 感谢您的评论和回答! I have completed my javascript code as follows:
我已经完成了如下的JavaScript代码:
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++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.