mongodb一条文档的值存的是数组,在更新的时候如何给数组push新的数据?
某草草
某草草 2017-05-02 09:24:04
0
2
642
db.col.insert({
    name: 'kad',
    tags: ['mongodb', 'database', 'NoSQL'],
})

我现在有了新的数据'mysql'需要添加到tags对应的数组中,如何push进去呢?

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

我想让结果变成 tags:['mongodb','database','NoSQL','mysql']

某草草
某草草

reply all(2)
曾经蜡笔没有小新

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.

滿天的星座

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template