MongoDB:使用同一文档中的数据更新文档 [英] MongoDB: Updating documents using data from the same document
本文介绍了MongoDB:使用同一文档中的数据更新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文档列表,每个文档都具有lat和lon属性(以及其他属性).
I have a list of documents, each with lat and lon properties (among others).
{ 'lat': 1, 'lon': 2, someotherdata [...] }
{ 'lat': 4, 'lon': 1, someotherdata [...] }
[...]
我想对其进行修改,使其看起来像这样:
I want to modify it so that it looks like this:
{ 'coords': {'lat': 1, 'lon': 2}, someotherdata [...]}
{ 'coords': {'lat': 4, 'lon': 1}, someotherdata [...]}
[...]
到目前为止,我已经知道了:
So far I've got this:
db.events.update({}, {$set : {'coords': {'lat': db.events.lat, 'lon': db.events.lon}}}, false, true)
但是它将 db.events.lat 和 db.events.lon 视为字符串.如何引用文档的属性?
But it treats the db.events.lat and db.events.lon as strings. How can I reference the document's properties?
干杯.
推荐答案
$ rename 运算符(在发布此问题后一个月推出),使您无需修改值就可以很轻松地完成这些事情.
The $rename operator (introduced a month after this question was posted) makes it really easy to do these kinds of things where you don't need to modify the values.
插入一些测试文档
db.events.insert({ 'lat': 1, 'lon': 2, someotherdata: [] })
db.events.insert({ 'lat': 4, 'lon': 1, someotherdata: [] })
使用$rename
运算符
use the $rename
operator
db.events.update({}, {$rename: {'lat': 'coords.lat', 'lon': 'coords.lon'}}, false, true)
结果
db.events.find()
{
"_id" : ObjectId("5113c82dd28c4e8b79971add"),
"coords" : {
"lat" : 1,
"lon" : 2
},
"someotherdata" : [ ]
}
{
"_id" : ObjectId("5113c82ed28c4e8b79971ade"),
"coords" : {
"lat" : 4,
"lon" : 1
},
"someotherdata" : [ ]
}
这篇关于MongoDB:使用同一文档中的数据更新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文