search

Home  >  Q&A  >  body text

The value of a document in mongodb is stored in an array. How to push new data to the array when updating?

db.col.insert({
    name: 'kad',
    tags: ['mongodb', 'database', 'NoSQL'],
})

I now have new data 'mysql' that needs to be added to the array corresponding to tags. How to push it in?

db.col.update({'name':'kad'},{$set:{'tags':'mysql'}}) 这样不是相当于覆盖了原来的数据么

I want the result to be tags:['mongodb','database','NoSQL','mysql']

某草草某草草2820 days ago684

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-02 09:26:04

    Please refer to

    db.col.update({name : "kad"}, { $push : { tags : "mysql"}})

    Also please refer to the official documentation:

    https://docs.mongodb.com/manu...

    Recommendation: Read more MongoDB documentation; MongoDB’s documentation is of high quality.

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-02 09:26:04

    Use addToSet

    db.col.update({"name":"kad"},{$addToSet:{"tags":"mysql"}});
    

    or use push

    db.col.update({"name":"kad"},{$push:{"tags":"redis"}});
    

    The difference between the two is that addToSet will only add it if it does not exist in the array. If it already exists, it will not add it. Push will insert the inserted value regardless of whether it is in the original array, that is, duplicate values ​​can be inserted.

    reply
    0
  • Cancelreply