假设我得到了以下文档,其中包含嵌入文档的数组:
{
"name" : "test",
"children" : [
{
"name" : "child1",
"children" : [
{
"name" : "sub1",
"children" : [
{"name" : "c1"},
{"name" : "c2"},
{"name" : "c3"},
{"name" : "c4"},
{"name" : "c5"}
]
}
]
},
{
"name" : "child2",
"children" : [
{
"name" : "sub2",
"children" : [
{"name" : "c1"},
{"name" : "c2"},
{"name" : "c3"},
{"name" : "c4"}
]
},
{
"name" : "sub3",
"children" : [
{"name" : "c1"},
{"name" : "c2"},
{"name" : "c3"},
{"name" : "c4"}
]
},
{
"name" : "sub4",
"children" : [
{"name" : "c1"},
{"name" : "c2"},
{"name" : "c3"},
{"name" : "c4"}
]
}
]
}
]
}
我们可以看到,test
有两个孩子:child1
和child2
,而一个孩子都有自己的孩子一样sub1
,sub2
,sub3
,sub4
,等,等。当前,我必须更新一些子级内容,但是遇到以下两个问题:
findOne()
,当我不小心打错字(名称child1
应为child2
)时:db.collection_name.findOne({
'name': 'test',
'children.name': 'child1', // -> should be `child2`
'children.children.name': 'sub2'
})
我仍然可以正确获取文档“测试”,但是由于我输入了错误并且sub2
实际上位于child2
,而不是之下child1
,那么我如何仍然可以获得此正确findOne()
结果?
updateOne()
,当我尝试更新child1
的array时children
,它运行良好(代码也类似于官方文档中的示例):db.collection_name.updateOne({
'name': 'test',
'children.name': 'child1' // locate child1
}, {
'$set':{'children.$.children':[some other content]}
})
但是,当我也尝试更新sub3
的数组(在之下child2
)时,同样的方法因error失败cannot use the part (children of children.children.1.children) to traverse the element
,这是有问题的代码:
db.collection_name.updateOne({
'name': 'test',
'children.name': 'child2',
'children.children.name': 'sub3' // locate sub3
}, {
'$set':{'children.children.$.children':[some other content]}
})
如果有人可以帮助解决这两个问题,我将非常感激,在此先感谢您!
对于第一个问题,您可以使用$elemMatch
查找确切的元素。
db.collection_name.findOne({
'name':'test',
children:{
$elemMatch:{
'name':'child2',
'children.name':'sub2'
}
}
})
我猜想mongo不支持多个嵌套数组更新,但是如果您知道子数组的位置,则可以使用此方法。
db.collection_name.updateOne({
'name':'test',
children:{
$elemMatch:{
'name':'child2',
'children.name':'sub3'
}
}
}
, {
$set: {"children.$.children.1.children" :
[
{"name" : "c1"},
{"name" : "c2"},
{"name" : "c3"},
{"name" : "c4"}
]
}
}
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句