我是一个MongoDB新手,想问如何编写涉及upsert和列表的更新命令。MongoDB - upsert涉及列表
基本上我要完成这样的事情:那
{"_id" : ObjectId("4c28f62cbf8544c60506f11d"),
"some_other_data":"goes here",
"trips": [
{"name": "2010-05-10",
"loc": [{"lat":21.321231, "lng": 16.8783234, "updated_at": "Mon May 10 2010 15:24:35"},
{"lat":21.321231, "lng": 16.8783234, "updated_at": "Mon May 10 2010 15:24:24"}]
},
{"name": "2010-05-08",
"loc": [{"lat":21.324239, "lng": 16.8735234, "updated_at": "Mon May 8 2010 11:18:05"},
{"lat":21.311234, "lng": 16.8743271, "updated_at": "Mon May 8 2010 11:17:55"},
{"lat":21.321238, "lng": 16.8782219, "updated_at": "Mon May 8 2010 11:17:45"}]
}
]}
注:
- 您如果行程不存在提供行程名称和 当前位置
- ,它需要创建
- trips.name应该是唯一的,以便 如果它存在ts,您追加到 位置数组
这是我写的位置操作符与$ push相结合的查询。
db.mycollection.update({"application_id": "MyTestApp",
"trips.name": "2010-05-10"},
{$push: {'trips.$.loc': {"lat":11, "lng":11} }},
true);
但是,这会导致数据是这样的:
> db.mycollection.find({"application_id":"MyTestApp"})
{ "_id" : ObjectId("4c29044ebf8544c60506f11f"),
"application_id" : "MyTestApp",
"trips" : { "$" : { "loc" : [ { "lat" : 11, "lng" : 11 } ] },
"name" : "2010-05-10" }
}
你可以看到,
- “旅行” 是不是数组
- 花 “$” 的字面和创建一个 钥匙与那(doh!)
到目前为止,我对MongoDB一直非常满意,但编写复杂查询的确存在陡峭的学习曲线。
任何反馈将不胜感激。
由于提前, 阿米
再次检查我的回答如下 - 我编辑它包含了我认为是解决(或者至少东西,应该让你非常接近) – nearlymonolith 2010-06-30 21:17:50
看到此[SO主题](http://stackoverflow.com/questions/17994552/mongodb-update-documents-in-anray/17995495#17995495)。 与此类似的东西。 – user10 2013-08-01 13:32:21