I'm trying to figure out how to update an item inside an array which is a part of a post. I did find this which looks closest to what I'm looking for: MongoDB Update Array element
But I dont have the specific post lined up first like this example seems to show. But I need to find the specific post using _id first, then update an item in the array from the resulted post.
Can I do this with one query or do I need to find the item first to then update it like the example shows in the other answer?
In the below json how could I update the first posts comments: first comment?
EDIT:
[{
"_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"
}]
您应该考虑使用$elemMatch
( 文档 ),如下所示:
.update({'_id': '52c06c86b78a091f26000001', 'comments' : {$elemMatch: {'_id': '_SvF-Ag4d6wFf9QR1KdAdFIpcCyI3cqm2F4rl3w7rdk='}}}, {$set : {'comments.$.comment': 'Lame dress!'}})
您可以在Mongo中使用位置运算符来访问特定的数组元素,如下所示
db.collection.update( { _id: 52c06c86b78a091f26000001 }, { $set: { "comments.$1.comment" : "dress" } } )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.