我有以下json结构:
{
"_id" : ObjectId("5203af83396d285ea2ecff8f"),
"brand" : "LG",
"comments" : [{
"user_id" : ObjectId("521b2785eda03d0f9cab3566"),
"text" : "Nice TV"
}],
"model" : "47LS5600",
"price" : 499.0,
"thumbnail" : "lg-47LS5600"
}
我需要在数组“comments”中插入一个新字段“datetime”,如下所示:
{
"_id" : ObjectId("5203af83396d285ea2ecff8f"),
"brand" : "LG",
"comments" : [{
"user_id" : ObjectId("521b2785eda03d0f9cab3566"),
"text" : "Nice TV",
"datetime": <value>
}],
"model" : "47LS5600",
"price" : 499.0,
"thumbnail" : "lg-47LS5600"
}
我试着用bellow指示:
db.tvs.update({ _id: ObjectId("5203af83396d285ea2ecff8f") }, { $addToSet: { "comments.1": { "datetime": Date() } } } )
但它没有在项目中插入字段,它会创建与该项目分开的另一个对象
答案 0 :(得分:1)
查看链接:
http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator
修改文件:http://docs.mongodb.org/manual/tutorial/modify-documents
查看此代码。
db.bios.update(
{ _id: 3 },
{ $set: {
mbranch: 'Navy',
'name.aka': 'Amazing Grace'
}
}
)