MongoDB保存和更新数组元素

时间:2016-06-24 07:26:58

标签: php mongodb

我已保存此当前值

db.mycol.save({name:'elbren',lastname:'antonio',subjects:{}})

结果:

"_id" : ObjectId("576db356332a8fc87bf769be"),
"name" : "elbren",
"lastname" : "antonio",
"subjects" : {

}

我需要的是这个结果:

"_id" : ObjectId("576db356332a8fc87bf769be"),
"name" : "elbren",
"lastname" : "antonio",
"subjects" : 
{
    {
         code: "sub1",
         Description: "desc1",
         Unit: 3
     },
     code: "sub2",
     Description: "desc2",
     Unit: 3

}

在这方面做的最好的事情是,我想将主题添加到_id?

2 个答案:

答案 0 :(得分:0)

要创建文档以获得理想的结果,只需直接编写:

db.mycol.save({name:'elbren',lastname:'antonio',subjects:{
    {
        code: "sub1",
        Description: "desc1",
        Unit: 3
    },
    code: "sub2",
    Description: "desc2",
    Unit: 3
}})

如果您想更改("修复")现有文档,则必须使用update

db.mycol.update(
    { name : "elbren", lastname : "antonio" },
    { $set: { subjects:{
                  {
                      code: "sub1",
                      Description: "desc1",
                      Unit: 3
                  },
                  code: "sub2",
                  Description: "desc2",
                  Unit: 3
              }
    }}
);

此处{ name : "elbren", lastname : "antonio" }是与您想要的文档匹配的查询,第二部分是update parameter

答案 1 :(得分:0)

使用" $ push" operator将数组添加到当前对象。

// in php e.g:
['$push'=>['fild_value'=>array('mail=>'me@mail.com','tag'=>'personal')]]

更多结果:

{
   "_id": 12345678,
   "fild_value": [
        {
        "mail":"me@mail.com",
        "tag":"personal"
         },
         {
          "mail":"job@mail.com",
          "tag":"worker"
          }
      ]
 }

MongoDB提供数组运算符($ push / $ pull,$ addToSet,$ elemMatch等...)