如何在mongodb中更新数据?
这是我收藏的实际结构
db.collection.find().pretty()
{
"_id" : ObjectId("557914833ac61e518e6103ab"),
"dataValue" : {
"value1" : [
"value1 A",
"value1 B"
]
}
}
我想在dataValue
中插入默认值db.collection.find().pretty()
{
"_id" : ObjectId("557914833ac61e518e6103ab"),
"dataValue" : {
"value1" : [
"value1 A",
"value1 B"
],
"default" : [
"default A",
"default B"
]
}
}
请帮帮我
答案 0 :(得分:1)
试试这个:
db.collection.update(
{ _id: ObjectId("557914833ac61e518e6103ab") }, //update doc with this id
{ $set:
{
"dataValue.default": [
"default A",
"default B"
]
}
}
)
根据我的评论:https://docs.mongodb.com/manual/reference/method/db.collection.update/
更新语法是(我们仅使用此
的<query>
和<update>
部分
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>
}
)
在您的情况下,您需要使用$set
dataValue.default
使用点符号“到达”子文档内部,并设置属性
答案 1 :(得分:0)
这可以通过使用$ set运算符
进行简单更新来实现db.collection.update({"_id" : ObjectId("557914833ac61e518e6103ab")},
{ $set: {"dataValue.default" : [
"default A",
"default B"
]}})