且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MongoDB:使用同一文档中的数据更新文档

更新时间:2022-02-11 22:59:34

$ 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" : [ ]
}