mongo用数字名称表示嵌入字段

时间:2017-09-19 19:25:13

标签: 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"等并更新一些东西。但我的问题是,当我从函数中引用字段时它不起作用。

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

如果我使用引号,则会打印字符串文字。我尝试使用$ with with with quotes但没有用。

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

我想这是由数字字段名称引起的。因为,在其他嵌入式领域,我获得了所需的输出。有什么方法可以解决这个问题吗?谢谢。

1 个答案:

答案 0 :(得分:1)

你应该试试这个:

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

> 2