我的文档结构是
"MainAccounts" : [
{
"orgs" : "5808ba773fe315441b9e0a9e",
"_id" : ObjectId("5808bc0c3fe315441b9e0b1a"),
"accounts" : [
"5808baf33fe315441b9e0aa7",
"5808baf33fe315441b9e0aa8",
"5808baf33fe315441b9e0aa9",
"5808baf33fe315441b9e0aa1"
]
},
{
"orgs" : "5808ba773fe315441b9e0a9f",
"_id" : ObjectId("5808bc0c3fe315441b9e0b1b"),
"accounts" : [
"5808baf33f35425852s255s7",
"5808baf3sd23s2d3d4w5s2s8",
"5808baf33sd211ds2d2sdsa9",
"5808baf33dssd2d21b9e0aa1"
]
}
],
我想提出一个特定的帐户说" 5808baf33fe315441b9e0aa8"从这里,我写了这样的查询。
{ $pull: { "MainAccounts.$.accounts": "5808baf33fe315441b9e0aa8"} }
它只给出错误"位置运算符没有找到查询所需的匹配项。未更新的更新:MainAccounts。$。accounts"
{ $pull: { "MainAccounts.0.accounts": "5808baf33fe315441b9e0aa8" } }
如果我这样给它,它将只删除那个给出预期输出的值。
我需要输出
"MainAccounts" : [
{
"orgs" : "5808ba773fe315441b9e0a9e",
"_id" : ObjectId("5808bc0c3fe315441b9e0b1a"),
"accounts" : [
"5808baf33fe315441b9e0aa7",
"5808baf33fe315441b9e0aa9",
"5808baf33fe315441b9e0aa1"
]
},
{
"orgs" : "5808ba773fe315441b9e0a9f",
"_id" : ObjectId("5808bc0c3fe315441b9e0b1b"),
"accounts" : [
"5808baf33f35425852s255s7",
"5808baf3sd23s2d3d4w5s2s8",
"5808baf33sd211ds2d2sdsa9",
"5808baf33dssd2d21b9e0aa1"
]
}
],
这里我无法从第二个数组中删除我需要提供的值
{ $pull: { "MainAccounts.1.accounts": "5808baf33fe315441b9e0aa8" } }
但我需要循环,任何帮助都表示赞赏。
答案 0 :(得分:0)
您将收到一个错误: “无法将$ pull应用于非数组值”
这应该是:
db.collection.update({'MainAccounts.accounts': '5808baf33fe315441b9e0aa8'}, {$pull: {MainAccounts:{ accounts: '5808baf33fe315441b9e0aa8'}}})
这里是对此的引用:
mongodb Cannot apply $pull/$pullAll modifier to non-array, How to remove array element
答案 1 :(得分:-1)
db.collection.update({someId,{$ pull:{&#34; MainAccounts&#34;:{&#34; accounts&#34;:&#34; 5808baf33fe315441b9e0aa8&#34;}}}}} < / p>
someId可能是你的_id。 请记住,如果您必须访问阵列内的文档,则无法访问它。只有运算符。你必须使用它的索引.mongodb可以访问它的另一种方法是使用大括号。
答案 2 :(得分:-1)
这将做你想要的:
db.collection.update({'MainAccounts.accounts': '5808baf33fe315441b9e0aa8'}, {$pull: {'MainAccounts.$.accounts': '5808baf33fe315441b9e0aa8'}})