我想在数组中取消设置多个对象..这是我的数据库数据
{
"_id" : ObjectId("5440e390fb038d3062000001"),
"firstname" : "demo2",
"contacts" : [
{
"contactId" : "544372d5f9ae85d0589d2b71",
"displayname" : "demo1",
"accounts" : {
"00e12ed769eb19239e218355cbe3c24f" : {
"type" : "mobile",
"userId" : "123456789",
"status" : 0,
}
}
},
{
"contactId" : "544372e4f9ae85d0589d2b72",
"displayname" : "demo2",
"accounts" : {
"00e12ed769eb19239e218355cbe3c24f" : {
"type" : "mobile",
"userId" : "123456789",
"status" : 0,
}
}
}
],
}
我使用了这个db查询,但它只更新了一条记录
db.users.update({'contacts.accounts.00e12ed769eb19239e218355cbe3c24f.userId':'123456789'},
{$unset:{'contacts.$.accounts.00e12ed769eb19239e218355cbe3c24f':''}},{multi:true})
它只更新一个,但我想更新多个项目......
答案 0 :(得分:1)
只需将更新语句包装成:
while (db.users.update({
'contacts.accounts.00e12ed769eb19239e218355cbe3c24f.userId' : '123456789'
}, {
$unset : {
'contacts.$.accounts.00e12ed769eb19239e218355cbe3c24f' : ''
}
}, {
multi : true
}).nMidified);
答案 1 :(得分:0)
db.users.find({'contacts.accounts.00e12ed769eb19239e218355cbe3c24f.userId':'123456789'}).forEach(function(item)
{
var contacts = item.contacts;
for(var i = 0; i < contacts.length; i++)
{
var contact = contacts[i];
delete contact.accounts['00e12ed769eb19239e218355cbe3c24f'];
}
// db.users.save(item);
// use update() instead of save(
db.users.update({'contacts.accounts.00e12ed769eb19239e218355cbe3c24f.userId':'123456789'}, item);
})