[英]How to push new items to an array inside of an object
我的JSON当前如下所示:
{
"_id" : 393,
"item" : 34,
"comments" : [
{
"name" : "kevin",
"messages" : [
"item",
"item"
]
},
{
"name" : "ryan",
"messages" : [
"item",
"item"
]
}
]
}
我如何将新项目推到留言数组中的评论数组中第一项或第二项?
db.newcon.update({_id: 393}, { $push: { comments['kevin']: {messages: 39 } } })
使用$ elemMatch和$
运算符可以更新文档,查询如下:
db.collectionName.update({"_id":393,"comments":{"$elemMatch":{"name":"kevin"}}},
{"$push":{"comments.$.messages":39}})
这样的事情会起作用:
var newMessage = '39';
comments.forEach(function(item) {
if (item.name === 'kevin') {
item.comments.push(newMessage);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.