【问题标题】:Insert data into inner array in MongoDB将数据插入MongoDB的内部数组
【发布时间】:2011-10-24 23:37:51
【问题描述】:

我有一个小问题,希望你能帮助我。 我在 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”向 cmets 插入新数据。但我尝试这样:

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

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

{
"_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
     }
]
}

我也试过了:

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

但什么都没有。

【问题讨论】:

    标签: php json mongodb database


    【解决方案1】:

    这在 mongo 控制台中运行良好 :)

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

    【讨论】:

    • 是的,你是对的;)非常感谢!你能告诉我char“$”在“list.$.cmets”中是什么意思吗?或者给我一个参考?谢谢!
    【解决方案2】:

    使用 $addToSet 修饰符,因为 cmets 是一个数组而不是字段。

    【讨论】:

    • 我将 '$push' 更改为 '$addToSet',但该代码具有与 '$push' 相同的行为(添加新字段,我显示有问题的示例)
    • 我还使用 '$push' 将数据添加到 'list' 数组中,它与 '$push' 一起使用。
    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2022-11-23
    相关资源
    最近更新 更多