使用 php 更新 mongodb 中的嵌入文档 [英] update an embedded document in mongodb using php

查看:39
本文介绍了使用 php 更新 mongodb 中的嵌入文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个博客网站,所以我使用 MongoDB 作为我的数据库.在我的文章"集合中,我有 1 个名为 posts 的嵌入式文档,我想再插入 1 个嵌入式文档.评论进去.

I am making a blogging site so I am using MongoDB as my DB. In my collection "articles", I have 1 embedded doc named posts and I want to insert 1 more embedded doc. comments into it.

数据库:

  {
    "_id": ObjectId("4f41a5c7c32810e404000000"),
    "username":"abc",
    "posts": [
    {
        "_id": 1,
        "content": "dskcnkdcnksldcnskcd",
        "title" : "test1"
    },
    {"_id": 2,
        "content": "dskcsdsl;d,cl;sdcl;sdmcnkdcnksldcnskcd",
        "title" : "test2"
    },
   ]
}

我想在帖子中插入评论.

I want to insert comments into posts.

 {
    "_id": ObjectId("4f41a5c7c32810e404000000"),
    "username":"abc",
    "posts": [
    {
        "_id": 1,
        "content": "dskcnkdcnksldcnskcd",
        "title" : "test1",
     "comments":[
    {
      "content": "usdhcjsdcjskd",
      "by" : "abc"
    }
    ]
    },
    {"_id": 2,
        "content": "dskcsdsl;d,cl;sdcl;sdmcnkdcnksldcnskcd",
        "title" : "test2"
    }
   ]
}

推荐答案

Comments 实际上是您文档中帖子的嵌入文档,因此您需要将查询稍微更改为:

Comments is actually an embedded document of posts in your document as such you need to change your query a little to:

$collection->update(array('_id' => new MongoId($bid),'posts.id'=> $pid),array('$push' => array('posts.$.comments' => $comment)));

试试看.

注意我是如何使用位置运算符的?您可以在此处阅读更多相关信息:http://www.mongodb.org/display/DOCS/Updating/#Updating-The%24positionaloperator

Notice how I have used the positional operator? You can read more about it here: http://www.mongodb.org/display/DOCS/Updating/#Updating-The%24positionaloperator

这篇关于使用 php 更新 mongodb 中的嵌入文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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