在MongoDB中将数据插入内部数组 [英] Insert data into inner array in MongoDB

查看:123
本文介绍了在MongoDB中将数据插入内部数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,希望你可以帮助我。
我在MongoDB中有下一个数组结构:

I have a little problem, hope You can help me. I have next array structure in MongoDB:

{
"_id":ObjectId("4e43cf96e7c7914b87d2e0ff"),
"list" :[
    {
    "id" : ObjectId("4e43cf96e62883ee06000002"),
    "user_name" : "login",
    "comments" : [ ]  //insert here new data
    },
    {
    "id" : ObjectId("4e43cf96e62883ee06000003"),
    "user_name" : "login",
    "comments" : [ ]
    }
]
}

我想通过list.id向注释插入新数据。但我尝试这样:

And I want to insert new data to comments by "list.id". But I try like that:

$post_id = "4e43cf96e62883ee06000002";
$this->connection->user->feed->update(
    array ('list.id' => new MongoId($post_id) ), 
    array ('$push' => array ('list'=>array('comments'=>$data ) ))
)

但是该代码在结构中创建了新字段,但是没有向字段comments添加数据:

But that code create new field in structure, but not add data to field 'comments':

{
"_id":ObjectId("4e43cf96e7c7914b87d2e0ff"),
"list" :[
     {
     "id" : ObjectId("4e43cf96e62883ee06000002"),
     "user_name" : "login",
     "comments" : [ ]  //insert here new data
     },    
     {
     "id" : ObjectId("4e43cf96e62883ee06000003"),
     "user_name" : "login",
     "comments" : [ ]
     },            
     {
     "comments" : { //added new field
        //there is my data
     }
]
}


b $ b

也尝试过:

Also I tried:

$this->connection->user->feed->update(
     array ('list.id' => new MongoId($post_id) ), 
     array ('$push' => array ('list.comments'=>$data ) ) 
  );

但没有。

推荐答案

这在mongo控制台中工作正常)。

This works fine in mongo console :)

db.yar.update({"list.id":ObjectId("4e43cf96e62883ee06000002")}, {"$addToSet":{"list.$.comments":"my cool comment"}});

这篇关于在MongoDB中将数据插入内部数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆