查找跨集合的匹配字段的文档,并从匹配的文档中添加新字段

时间:2017-02-24 04:33:33

标签: mongodb

我有收藏集carsregistrationscar_specs

我需要创建两个新的集合

  1. cars_registrations - 对于具有相同RegNoregistrations的文档,这会将carsStreetNo添加到HouseNo,从而丢弃文档没有比赛。

  2. cars_registrations_spec - 这会为CarSpeccar_specs集合添加cars_registrations,以查找具有相同StreetNoHouseNo的文档。< / p>

  3. 从控制台执行此操作的最有效方法是什么?cars集合中有500K文档,registrations集合中有50K文档。

    汽车:

    [
            { "StreetNo": 321, "HouseNo": "12",  "Car": "camry" },
            { "StreetNo": 321, "HouseNo": "13",  "Car": "camry" },
            { "StreetNo": 323, "HouseNo": "12",  "Car": "accord" },
            { "StreetNo": 324, "HouseNo": "15",  "Car": "Sunny" }
        ]
    

    注册

    [
            { "StreetNo": 321, "HouseNo": "12",  "RegNo": "1122" },
            { "StreetNo": 321, "HouseNo": "13",  "RegNo": "1123" },
            { "StreetNo": 323, "HouseNo": "12",  "RegNo": "1124" },
        ]
    

    cars_registrations

    [
            { "StreetNo": 321, "HouseNo": "12",  "Car": "camry",  "RegNo": "1122"  },
            { "StreetNo": 321, "HouseNo": "13",  "Car": "camry",  "RegNo": "1123" },
            { "StreetNo": 323, "HouseNo": "12",  "Car": "accord",  "RegNo": "1124" }
        ]
    

    car_specs

    [
            { "StreetNo": 321, "HouseNo": "12",  "CarSpec": {"cyl": "4", "gear": "5"} },
            { "StreetNo": 321, "HouseNo": "13",  "CarSpec": {"cyl": "4", "gear": "5"} },
            { "StreetNo": 323, "HouseNo": "12",  "CarSpec": {"cyl": "6", "gear": "7"} }
        ]
    

    cars_registrations_spec

    [
            { "StreetNo": 321, "HouseNo": "12",  "Car": "camry",  "RegNo": "1122",  "CarSpec": {"cyl": "4", "gear": "5"} },
            { "StreetNo": 321, "HouseNo": "13",  "Car": "camry",  "RegNo": "1123",  "CarSpec": {"cyl": "4", "gear": "5"} },
            { "StreetNo": 323, "HouseNo": "12",  "Car": "accord", "RegNo": "1124", "CarSpec": {"cyl": "6", "gear": "7"} }
        ]
    

    以下是一种尝试的方法。但是,这需要永远完成集合中的文档数量 - 这样做的mongodb way是什么?

    for cars_registrations

    var results = db.registrations.find({}, {_id: 0}).toArray();
    for( var i = 0; i < results.length; i++) {
        var car = db.car.findOne({$and: [{StreetNo: results[i]["StreetNo"]},
        {HouseNo: results[i]["HouseNo"]}] }, {_id: 0});
        if(car && results[i]["RegNo"]) {
            car["RegNo"] = results[i]["RegNo"]
            db.cars_registrations.insertOne(car);
        }
    }
    

    我遇到的问题是它需要很长时间 - 很多小时 - 我的猜测findOne $and需要花费很多时间 - 对我来说需要花费很多时间在拥有500K文档和50K文档注册集合的汽车收藏中完成此操作。这通常花费这么多时间吗?

0 个答案:

没有答案