我有这些数据:
_id : 1
status:1,
name:"name",
details:
{
crm:115,
webs:
{ tag:"blog" , url:"http://..."},
contacts:
{
_id:1,
name:"me",
phones:
{ tag:"home", number:"123..." },
{tag:"mobile", number:"123456789"}
}
}
我希望使用{tag:office", number:"9823..."}
该命令/查询是什么?
答案 0 :(得分:2)
您可以使用以下查询轻松将其推送到数组中(我必须修改您粘贴的JSON,因为它无效一点):
db.collection.drop();
db.collection.insert( {
_id : 1,
status: 1,
name: "name",
details: {
crm:115,
webs: {
tag:"blog",
url:"http://..."
},
contacts: {
_id: 1,
name: "me",
phones: [
{ tag: "home", number: "123..." },
{ tag:"mobile", number:"123456789" }
]
}
}
} );
db.collection.update(
{ _id: 1 },
{ $push : { 'details.contacts.phones' : { tag:"office", rname:"9823" } } }
);
db.collection.find().pretty();
{
"_id" : 1,
"details" : {
"contacts" : {
"_id" : 1,
"name" : "me",
"phones" : [
{
"tag" : "home",
"number" : "123..."
},
{
"tag" : "mobile",
"number" : "123456789"
},
{
"tag" : "office",
"rname" : "9823"
}
]
},
"crm" : 115,
"webs" : {
"tag" : "blog",
"url" : "http://..."
}
},
"name" : "name",
"status" : 1
}
答案 1 :(得分:0)
$push
运算符的值必须引用要更新的数组。因此,当数组字段嵌入其他文档时,您需要使用点符号,如下所示:
db.abcd.update({_id: 1},
{$push: {"details.contacts.phones": {tag:"office", rname:"9823"}}});