2017-06-20 56 views
0

想象我有一个像如何阵推新领域的MongoDB

{ 
    "_id" : ObjectId("594994d1ab6c161168aa5969"), 
    "user_id" : ObjectId("594994d1ab6c161168aa5968"), 
    "active" : [ 
     { 
      "type" : "active" 
     }, 
     { 
      "type" : "inactive" 
     } 
    ] 
} 

我想添加到第一对象有源阵列数据库。这是导致我的预期

{ 
    "_id" : ObjectId("594994d1ab6c161168aa5969"), 
    "user_id" : ObjectId("594994d1ab6c161168aa5968"), 
    "active" : [ 
     { 
      "type" : "active", 
      "note": [{ 
          content: 'here is content', 
          title : ' here is title' 
         }] 
     }, 
     { 
      "type" : "inactive" 
     } 
    ] 
} 

这里是代码我试过

db.collection('..').update({'user_id' : ObjectId(userId)} , 
{$push:{ "active.0": "note": [{ 
           content: 'here is content', 
           title : ' here is title' 
         }] }) 

,但我得到The field 'active.0' must be an array but is of type object in document。我的错在哪里?请帮助

+1

应该是'{$ push:{“active.0.note”:{content:'here is content',title:'here is title'}}}' –

+0

@NeilLunn我试过这个,它创建了新的字段db中的活动[0] –

+0

@NeilLunn我想将它添加到数组的第一个对象活动 –

回答

1

与您的文档这样开始:

{ 
    "_id" : ObjectId("594994d1ab6c161168aa5969"), 
    "user_id" : ObjectId("594994d1ab6c161168aa5968"), 
    "active" : [ 
     { 
      "type" : "active" 
     }, 
     { 
      "type" : "inactive" 
     } 
    ] 
} 

您运行$push这样的:

db.collection.update(
    { "_id" : ObjectId("594994d1ab6c161168aa5969") }, 
    { "$push":{ "active.0.note": { content: 'here is content', title : ' here is title' } } } 
) 

哪像这样的第一个元素中创建新的数组:

{ 
     "_id" : ObjectId("594994d1ab6c161168aa5969"), 
     "user_id" : ObjectId("594994d1ab6c161168aa5968"), 
     "active" : [ 
       { 
         "type" : "active", 
         "note" : [ 
           { 
             "content" : "here is content", 
             "title" : " here is title" 
           } 
         ] 
       }, 
       { 
         "type" : "inactive" 
       } 
     ] 
} 

这里的一切都是从我的外壳上剪下来的。