[英]MongoDB update an array element matching a condition using $push
I'm using Python and Mongo for the fist time together and in documentation I wasn't able to find what I need. 我第一次使用Python和Mongo,在文档中找不到我需要的东西。
So my data object looks like this 所以我的数据对象看起来像这样
{
"_id" : ObjectId("54d372597d74523bc6991b9b"),
"id_user" : "2000001",
"date_registrated" : "2015-01-21 12:11:28.185",
"user" : "Bogdan",
"gender" : "M",
"email" : "a@a.com",
"charachters" : [
{
"quest_info" : "TUT_var,1421842359 STARTAREA,4 ",
"char_name" : "Testarion"
}
]
}
And I want to add new field into existing charachters, something like 我想将新字段添加到现有角色中,例如
party_user = {"party_name": "name",
"admin": 0}
And finally I want to get this: 最后,我想得到这个:
{
"_id" : ObjectId("54d372597d74523bc6991b9b"),
"id_user" : "2000001",
"date_registrated" : "2015-01-21 12:11:28.185",
"user" : "Bogdan",
"gender" : "M",
"email" : "a@a.com",
"charachters" : [
{
"quest_info" : "TUT_var,1421842359 STARTAREA,4 ",
"char_name" : "Testarion"
**"parties" : [{party 1},{party 2}]**
}
]
}
The problem is how to create query that makes that ? 问题是如何创建查询呢? I've tried with something like this but it failed miserably:
我已经尝试过类似的方法,但是失败了:
db.collection('MyDB').update(
{"char_name": "Testarion"},
{"$push": {
"charachters": {"parties": party_user}
}})
I'm still new with Mongo and haven't catched up all the things but can you please show me what am I doing wrong ? 我对Mongo还是很陌生,还没有掌握所有内容,但是请您告诉我我做错了什么吗? Is that even possible ?
那有可能吗?
Use '$' in your update query for that array element: 在更新查询中对该数组元素使用“ $”:
db.collection.update(
{"charachters.char_name": "Testarion"},
{"$push": {"charachters.$.parties": "party_user"}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.