在mongodb中的单个文档的字段中添加数据

时间:2013-07-11 12:22:23

标签: mongodb

我有这些数据:

_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..."}

在“手机”中再输入一个条目

该命令/查询是什么?

2 个答案:

答案 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"}}});