尽管查询只返回一个,但查找返回数组中所有项的查询

时间:2017-03-16 11:03:03

标签: java mongodb mongodb-java

我正在编写一个查询,只对数组中的一个项目起作用,但查询返回整个数组。

我有一个包含这样数据的集合:

"testScenarioId":"100",
"testSteps":[

  {
     "edit":false,
     "controlId":1450419683150,
     "controlName":"scanTextBox",
     "objProp":"id->articleSearch_scanViewPopup_field",
     "objPropType":15,
     "action":{
        "id":6
     },
     "screenId":1450419663920,
     "screenName":"Order.Scan",
     "applicationId":4,
     "applicationName":"GSM",
     "testCaseId":"100",
     "index":1,
     "testStepNumber":"1"
  },
  {
     "edit":false,
     "controlId":1450419683894,
     "controlName":"scansearchbutton",
     "objProp":"id->articleSearch_scanViewPopup_field_HelpIcon",
     "objPropType":17,
     "action":{
        "id":2
     },
     "screenId":1450419663920,
     "screenName":"Order.Scan",
     "applicationId":4,
     "applicationName":"GSM",
     "testCaseId":"100",
     "index":2,
     "testStepNumber":"2"
  }]}

我想根据条件"testScenarioId" : "100""testSteps.testStepNumber" : "1"更新收藏品;这意味着必须更新testSteps数组中的第一个文档,如下所示

{

 "edit":false,
 "controlId":1450419683150,
 "controlName":"scanTextBox",
 "objProp":"id->articleSearch_scanViewPopup_field",
 "objPropType":15,
 "action":{
    "id":6
 },
 "screenId":1450419663920,
 "screenName":"Order.Scan",
 "applicationId":4,
 "applicationName":"GSM",
 "testCaseId":"100",
 "index":1,
 "testStepNumber":"1"

}

但是当我运行这个命令时,我很惊讶:

db.TestSteps.find({"testScenarioId":"100","testSteps.testStepNumber":"1"})
在mongo shell中,我得到了所有 testSteps数组中的文档。

编辑:我想知道Java代码,使用上述标准更新数组中的文档。

先谢谢。

3 个答案:

答案 0 :(得分:0)

尝试在查找查询中添加$elemMatch

db.TestSteps.find({"testScenarioId":"100", "testSteps": $elemMatch: {"testStepNumber":"1"}})

答案 1 :(得分:0)

您需要添加投影。

 db.TestSteps.find( { "testScenarioId":"100"},{"testSteps": { $elemMatch: {"testStepNumber":"1" } } } )

答案 2 :(得分:0)

查询文件

您可以使用projection的{​​{1}}参数中的$ projection operator

find命令的语法是:

find

所以这应该有效:

find(query, projection)
  • 请注意,当您指定db.TestSteps.find({"testScenarioId":"100","testSteps.testStepNumber":"1"}, { 'testSteps.$': 1 }) 时,只会显示所选字段,因此如果您还需要返回其他字段,请将它们添加到投影中。 详细了解投影here

更新文件

要根据搜索到的数组元素进行更新,您还可以使用$:

projection

$ set中的$ operator仅定位查询中匹配的第一个数组元素

使用查找,修改元素并将其保存回来

你需要:

  1. 使用数组元素
  2. 获取文档
  3. 仅提取doc
  4. 中的元素
  5. 将元素修改为您想要的内容
  6. 将其保存回相同的位置 - 覆盖原始元素

  7. db.TestSteps.update(
      {"testScenarioId":"100","testSteps.testStepNumber":"1"},
      {$set: {'testSteps.$.new_field': 'hello world'}}
    )