我正在编写一个查询,只对数组中的一个项目起作用,但查询返回整个数组。
我有一个包含这样数据的集合:
"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代码,使用上述标准更新数组中的文档。
先谢谢。
答案 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仅定位查询中匹配的第一个数组元素。
使用查找,修改元素并将其保存回来
你需要:
db.TestSteps.update(
{"testScenarioId":"100","testSteps.testStepNumber":"1"},
{$set: {'testSteps.$.new_field': 'hello world'}}
)