How to push new items to an array inside of an object

后端 未结 2 866
时光取名叫无心
时光取名叫无心 2021-01-22 03:45

My JSON currently looks like this:

{
    \"_id\" : 393,
    \"item\" : 34,
    \"comments\" : [
        {
            \"name\" : \"kevin\",
            \"message         


        
相关标签:
2条回答
  • 2021-01-22 04:26

    Using $elemMatch and $ operator you can update your documents check below query :

    db.collectionName.update({"_id":393,"comments":{"$elemMatch":{"name":"kevin"}}},
                             {"$push":{"comments.$.messages":39}})
    
    0 讨论(0)
  • 2021-01-22 04:36

    Something like this will work:

    var newMessage = '39';
    comments.forEach(function(item) {
       if (item.name === 'kevin') {
            item.comments.push(newMessage);
       }
    });
    
    0 讨论(0)
提交回复
热议问题