有一个 $push 运算符用于将指定的值附加到数组中。假设我们有以下博客文章模式。帖子中已经有两个 cmets,如果您想在帖子中添加其他评论,可以使用 $push 运算符。我已经编写了一个示例代码来向节点中的以下架构插入注释,但您也可以在任何 .NET 中使用该逻辑
{
"_id" : ObjectId("55d58d05471d5cc42aaaef1b"),
"title" : "How to drop a collection in MongoDB?",
"author" : "dp123",
"body" : "body part goes ........!!!",
"permalink" : "How_to_drop_a_collection_in_MongoDB",
"tags" : [
"MongoDB",
"Mongod",
"mongo"
],
"comments" : [
{
"author" : "DP",
"body" : "awesome ......",
"email" : "dp@tektak.com"
},
{
"author" : "John",
"body" : "This article is really useful for me. I am not getting solution since last few week but finally I got it. Thank you very much!!!",
"email" : "john@gmail.com"
}
],
"date" : ISODate("2015-08-20T08:17:09.541Z")
}
**The code snippet is given below:**
var comment = {'author': name, 'body': body};
if (email != "") {
comment['email'] = email;
}
var query ={'permalink': permalink};
var operation ={'$push':{'comments': comment}};
db.collection('posts').update(query, operation, function (err, updated){
console.log("Successfully added the comment!!!");
});
我们可以在http://docs.mongodb.org/manual/reference/operator/update/push/获取有关 $push 的详细信息