简体   繁体   English

MongoDB:如何在不知道字段名称的情况下读取值?

[英]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.

相关问题 如何在不知道数组名称的情况下获取数组的值 - How do I get the value of an Array without knowing the name of the Array 如何在不知道值名的情况下从 JSON 文件中获取单个值和值名 - How to get a single value and value name from an JSON file without knowing the value name 如何在不知道名称的情况下访问对象 - How to access an object without knowing its name 使用Javascript Fetch API读取文件而无需知道文件名 - Read file with Javascript Fetch API without knowing the name of the file 如何在不知道Java中ID的情况下获取输入文本字段的值 - How to get value of input text field without knowing its id in Javascript 在不知道其名称的情况下检索JS的对象值 - Retrieving JS' Object value without knowing it's name 如何在不知道mongodb中的父键的情况下查找特定的嵌套对象 - How to find specific nested objects without knowing the parent key in mongodb 如何在事先不知道输入字段的 id 或 class 名称的情况下从不同网站检索输入值? - how do i retrieve input values from different websites without knowing the id or class name of the input field beforehand? 如何遍历数组字典(不知道键名) - How to iterate over a dictionary of arrays (without knowing the key name) 如何在不知道域名的情况下跟踪网站的浏览量? - how to track pageviews of a website without knowing its domain name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM