转换包含嵌套对象的Mongodb模式 [英] Convert Mongodb schema including nested Object

查看:83
本文介绍了转换包含嵌套对象的Mongodb模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设像这样的mongodb收集模式:

Suppose a mongodb collection schema like this:

{
   "_id"         : ObjectId("5a5b2657a19692e18a3792ad"),
   "Toponym"     : "Climate station Stavenhagen",
   "Lat"         : 53.33333,
   "Lon"         : "13.99999",
   "SensorMaker" : "Hitachi",
   "SensorClass" : "Thermometer",
   "Dimension"   : "SoilTemperature_0.05mSensor1",
   "Gauge"       : "degC"
}

我想将完整的收藏集(约90k件商品)更改为此,以符合最小的GeoJson:

And I would like to change the complete collection (~ 90k items) to this, to conform to minimal GeoJson:

{
  "_id"         : ObjectId("5a5b2657a19692e18a3792ad"),
  "Toponym"    : "Climate station Stavenhagen",
  "geometry"   : {
       "type"        : "Point", 
       "coordinates" : [53.33333, 13.99999]
       },
  "SensorMaker": "Hitachi",
  "SensorClass": "Thermometer",
  "Dimension"  : "SoilTemperature_0.05mSensor1",
  "Gauge"      : "degC"
}

我尝试使用此查询将其转换,但是无论如何我都会收到类似第5行:意外的字符串"之类的错误消息:

I tried to convert it using this query, but whatever I do I will receive an error the like "Line 5: Unexpected string":

db.sensor_geo.aggregate([
{ '$group' : {
    '_id' : '$_id',
    'Toponym' : '$Toponym'
    'geometry': { 'type': 'Point', { $set : {"coordinates.$[]": [ {'$Lat', '$Lon'} ] }}},
    'SensorMaker' : '$SensorMaker',
    'SensorClass' : '$SensorClass',
    'Dimension'   : '$Dimension',
    'Gauge'       : '$Gauge'
   } 
}
]);

我是否应该使用$push而不是$set,即使这样做也无济于事?我还必须为嵌套对象创建一个ObjectID,这可能会导致问题吗?

Should I've used $push instead of $set, even though this also lead nowhere? Do I also have to create an ObjectID for the nested Object, and that may have caused the problem?

推荐答案

您可以在聚合管道下面尝试批量写入.

You can try below aggregation pipeline with bulk writes.

以下聚合将通过批量更新将纬度和经度字段更改为几何,以写入新的几何字段并删除纬度​​和经度字段.

Below aggregation changes the Lat and Lon field to geometry with bulk update to write the new geometry field and remove the Lat and Lon fields.

var bulk = db.getCollection("sensor_geo").initializeUnorderedBulkOp();
var count = 0;
var batch = 1;

db.getCollection("sensor_geo").aggregate([
{"$project":{
    "geometry":{
      "type":"Point", "coordinates":["$Lat", "$Lon"]
    }
}}]).forEach(function(doc){ 
    var _id = doc._id; 
    var geometry = doc.geometry; 
    bulk.find({ "_id" : _id }).updateOne(
      {
        $set: {"geometry":geometry},
        $unset: {"Lat":"", "Lon":""}
      }
   ); 
    count++;  
    if (count == batch) { 
        bulk.execute(); 
        bulk = db.getCollection("sensor_geo").initializeUnorderedBulkOp(); 
        count = 0;
    } 
});

if (count > 0) { 
    bulk.execute(); 
}

这篇关于转换包含嵌套对象的Mongodb模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆