0

我有这个数据:

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

那将是什么命令/查询?

4

2 回答 2

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
}
于 2013-07-11T13:10:41.287 回答
0

运算符的值$push必须引用要更新的数组。因此,当数组字段嵌入到其他文档中时,您需要像这样使用点表示法:

db.abcd.update({_id: 1}, 
    {$push: {"details.contacts.phones": {tag:"office", rname:"9823"}}});
于 2013-07-11T13:08:42.790 回答