更新MongoDB中的嵌入式文档 [英] Update embedded documents in MongoDB
问题描述
我作为测试人员制作了一个收集帖子,现在包括2个文件。它有一个嵌入式集合注释,我输入了2个文档。评论有标题,内容和喜欢。我想知道如何添加另一个名为回复的集合字段(基本上是对评论的回复)?
这是我的初始文档的插入代码:
post = db.post< br />
post.insert< br>< br />
(< br />
[< br />
{title:我的第一个帖子,< br />
内容:Hello World这是我在网站上的第一篇文章!!!,< ; br />
时间:新日期(),< br />
by:{< br />
名称:Mohit Hiralal,< br />
电子邮件:mh@gmail.com}< br />
},< br />
{标题:我的第二个帖子,< br />
内容:这是我的第二篇文章。希望这能引起一些注意!,< br />
时间:新日期(),< br />
by {< br />
名称:Mohit,电子邮件:m@gmail.com< br />
},< br />
评论:< br />
[ < br />
{title:拼写错误,< br />
内容:你拼写错误......,< br />
l ikes:1009}< br />
]< br />
}< br />
]< br />
)
主要有两种方法可以达到这个目标。
你可以嵌入回复作为帖子文件中的字段。类似于:
post.insert
(
[
// ...
条评论:
[
{title: 拼写错误,
内容: 你拼写错误......,
喜欢: 1009 ,
回复:[] }
]
// ...
]
);或者,使用另一个集合来获取包含相应注释的键值的回复(如在关系数据库中)。 / p>
有关更多信息,请参阅MongoDB文档:数据建模。
I have made a collection post just as a tester which for now includes 2 documents. It has an embedded collection comments where i have entered 2 docs. A comment has a title, content and likes. I would like to know how could I add another field which is a collection named replies(Basically replies to the comments)?
Here is my insert code for the initial documents:
post=db.post<br /> post.insert<br><br /> (<br /> [<br /> {title:"My first Post",<br /> content:"Hello World this is my first post at the website!!!",<br /> time: new Date(),<br /> by:{<br /> name: "Mohit Hiralal",<br /> email:"mh@gmail.com"}<br /> },<br /> {title:"My second post",<br /> content:"This is my second post. Hope this garners some atention!",<br /> time: new Date(),<br /> by{<br /> name:"Mohit",email:"m@gmail.com"<br /> },<br /> comments:<br /> [<br /> {title:"Spelling wrong",<br /> content:"You spelled attenttion wrong…",<br /> likes:1009}<br /> ]<br /> }<br /> ]<br /> )
Mainly, there are 2 approaches to achieve that goal.
You can embed the replies as a field in the post document. Something like:
post.insert ( [ // ... comments: [ {title:"Spelling wrong", content:"You spelled attenttion wrong…", likes:1009, replies: []} ] // ... ] );Or, using another collection for replies that holds the key-value of the appropriate comment (like in relational databases).
For more information you can see the MongoDB documentation about: Data Modeling.
这篇关于更新MongoDB中的嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!