我正在试图弄清楚如何更新作为帖子一部分的数组中的项目。 我确实找到了最接近我正在寻找的东西:MongoDB Update Array element
但我没有特定的帖子排在第一位,就像这个例子似乎表明的那样。但是我需要首先使用_id找到特定的帖子,然后从结果帖子中更新数组中的项目。
我可以使用一个查询执行此操作,还是首先需要找到该项目,然后像其他答案中的示例所示更新它?
在下面的json中我怎么能更新第一篇帖子评论:第一条评论?
编辑:
[{
"_id": "52c06c86b78a091f26000001",
"comments": [
{
"user_id": "52ad97bab142627664000001 ",
"username": "phacer",
"comment": "nice dress!!!",
"created": 1390668491909,
"_id": "_SvF-Ag4d6wFf9QR1KdAdFIpcCyI3cqm2F4rl3w7rdk="
},
{
"user_id": "52ad97bab142627664000001 ",
"username": "phacer",
"comment": "nice dress!!!",
"created": 1390668491909,
"_id": "_SvF-Ag4d6wFf9QR1KdAdFIpcCyI3cqm2F4rl3w7rdk="
}
],
"desc": "Something somethingson",
"hate": [],
"imageurl": "some url",
"love": [
{
"user_id": "52add4f4344e8ca867000001",
"username": "asd",
"created": 1390652212592
}
],
"tags": [
{
"y": 29.3,
"brand": "Zara",
"type": "Bow Tie",
"x": 20,
"color": "Black"
}
],
"user_id": "52add4f4344e8ca867000001"
},
{
"_id": "52c06c86b78a091f26000001",
"comments": [
{
"user_id": "52ad97bab142627664000001 ",
"username": "phacer",
"comment": "nice dress!!!",
"created": 1390668491909,
"_id": "_SvF-Ag4d6wFf9QR1KdAdFIpcCyI3cqm2F4rl3w7rdk="
}
],
"desc": "Something somethingson",
"hate": [],
"imageurl": "some url",
"love": [
{
"user_id": "52add4f4344e8ca867000001",
"username": "asd",
"created": 1390652212592
}
],
"tags": [
{
"y": 29.3,
"brand": "Zara",
"type": "Bow Tie",
"x": 20,
"color": "Black"
}
],
"user_id": "52add4f4344e8ca867000001"
}]
答案 0 :(得分:2)
您应该考虑使用$elemMatch
(Documentation),如下所示:
.update({'_id': '52c06c86b78a091f26000001', 'comments' : {$elemMatch: {'_id': '_SvF-Ag4d6wFf9QR1KdAdFIpcCyI3cqm2F4rl3w7rdk='}}}, {$set : {'comments.$.comment': 'Lame dress!'}})
答案 1 :(得分:0)
您可以使用Mongo中的位置运算符来访问特定的数组元素,如下所示
db.collection.update( { _id: 52c06c86b78a091f26000001 }, { $set: { "comments.$1.comment" : "dress" } } )