Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb mongo指带有数字名称的嵌入式字段_Mongodb_Mongodb Query - Fatal编程技术网

Mongodb mongo指带有数字名称的嵌入式字段

Mongodb mongo指带有数字名称的嵌入式字段,mongodb,mongodb-query,Mongodb,Mongodb Query,我的mongo文档如下所示 { "_id": ObjectId("59b0ee362976fb61fc54708d"), "id_str": "29979814", "eventCat": { "1": [2], "2": [10, 5, 2, 2, 10], "7": [10], "8": [10, 5] } } 我想检查“eventCat.1”或“eventCat.2”等的存在,并更新一些内容。但我的问题是,当我引用函数中的字段时,它不起作用

我的mongo文档如下所示

{
  "_id": ObjectId("59b0ee362976fb61fc54708d"),
  "id_str": "29979814",
  "eventCat": {
    "1": [2],
    "2": [10, 5, 2, 2, 10],
    "7": [10],
    "8": [10, 5]
  }
}
我想检查“eventCat.1”或“eventCat.2”等的存在,并更新一些内容。但我的问题是,当我引用函数中的字段时,它不起作用

db.testCorpus.find({"id_str" : "29979814"}).forEach( function (x) { 
  tmp=x.eventCat.1; 
  if(tmp != null) {  
    print(x.eventCat.1); 
  } 
})
2017-09-20T00:08:53.115+0530 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell):1:98
如果我使用引号,它会打印字符串文字。我尝试使用带引号和不带引号的$,但没有效果

db.testCorpus.find({"id_str" : "29979814"}).forEach( function (x) { 
  tmp='$x.eventCat.1'; 
  if(tmp != null) {  
    print(tmp); 
  } 
})
> $x.eventCat.1
我猜这是由于数字字段名造成的。因为,在其他嵌入式字段中,我得到了所需的输出。有什么办法解决这个问题吗?谢谢。

您应该试试这个:

db.testCorpus.find({"id_str" : "29979814"}).forEach( function (x) { 
  tmp=x.eventCat['1']; 
  if(tmp != null) {  
    print(x.eventCat['1']); 
  } 
})

> 2

嵌入字段的行为是否类似于关联数组?工作得很有魅力!谢谢@Julien.In javascript对象(这里是嵌入字段)是关联数组。mongodb使用javascript脚本。因此,是的,嵌入字段的行为类似于关联数组
foo.bar
foo['bar']