сопоставить массив идентификатора и получить значение через поиск mongoDB - PullRequest
0 голосов
/ 04 мая 2018

Моя коллекция Стуктура, как показано ниже:

 {"_id" : ObjectId("5aec2ce5020ba15d2fb2665a"),
"password" : "e10adc3949ba59abbe56e057f20f883e",
"unique_id" : 22,
"first_name" : "Foram",
"last_name" : "Test ",
"country_phone_code" : "+61",
"email" : "a@a.com",
"phone" : "1231231231",
"device_type" : "android",
"admintypeid" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
"vehicle_detail" : [ 
    {
        "service_name" : "You",
        "_id" : ObjectId("5aec2d08020ba15d2fb2665c"),
        "name" : "Qee",
        "plate_no" : "Qwe111",
        "model" : "Qee",
        "color" : "Blue",
        "passing_year" : "2005",
        "service_type" : [ 
            ObjectId("5a9f9c53b9e8fa66f9b934c1")
        ],
        "admin_type_id" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
        "is_selected" : true,
        "pictureData" : "vehicle_images/5aec2d08020ba15d2fb2665cWjyP.jpg"
    }, 
    {
        "pictureData" : "vehicle_images/5aec35e00efc106080e14ec7y2tO.jpg",
        "is_selected" : false,
        "admin_type_id" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
        "service_type" : [ 
            ObjectId("5a9f9c53b9e8fa66f9b934c1"), 
            ObjectId("5ac954b7075e16583dc3311f")
        ],
        "passing_year" : "2018",
        "color" : "No",
        "model" : "Bcs",
        "plate_no" : "12112",
        "name" : "Bcs",
        "_id" : ObjectId("5aec35e00efc106080e14ec7"),
        "service_name" : "You"
    }
],
"service_type" : [ 
    ObjectId("5a9f9c53b9e8fa66f9b934c1")
],
"is_vehicle_document_uploaded" : true,
"is_trip" : [],
"__v" : 14
}

я хочу использовать идентификаторы campare в массиве service_type, который находится в массиве vehicle_detail в другую коллекцию с именем city_types, кроме того, что я должен сопоставить typid коллекции city_types с коллекцией tyes и получить значение name из коллекции типов

моя коллекция city_type будет выглядеть примерно так:

{
"_id" : ObjectId("5a9f9c53b9e8fa66f9b934c1"),
"countryid" : ObjectId("5abb275fd20731597cc01229"),
"cityid" : ObjectId("5abb27cbd20731597cc0122a"),
"typeid" : ObjectId("5a9f9b55b9e8fa66f9b934c0")
"__v" : 0}

, содержащий type_id

и моя коллекция типов как ниже

{
"_id" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
"typename" : "You",
"description" : "KARRU You",
"__v" : 0,
"main_type" : 0

}

что я хочу это имя типа

с идентификатором

Я использовал код ниже:

exports.get_provider_vehicle_list = function (req, res, next) {

var mongoose = require('mongoose');
var Schema = mongoose.Types.ObjectId;
var condition = {$match: {"_id": Schema(req.body.provider_id)}};
var vunwind = {$unwind: "$vehicle_detail"}

var lookup = {
    $lookup:
            {
                from: "types",
                localField: "vehicle_detail.admin_type_id",
                foreignField: "_id",
                as: "type_detail"
            }
};
var unwind = {$unwind: {
        path: "$type_detail",
        preserveNullAndEmptyArrays: true
    }
};

var group = {$group: {
        _id: null,
        "vehicle_detail": {$push: {
                is_selected: "$vehicle_detail.is_selected",
                admin_type_id: "$vehicle_detail.admin_type_id",
                service_type: "$vehicle_detail.service_type",
                passing_year: "$vehicle_detail.passing_year",
                color: "$vehicle_detail.color",
                model: "$vehicle_detail.model",
                plate_no: "$vehicle_detail.plate_no",
                name: "$vehicle_detail.name",
                _id: "$vehicle_detail._id",
                type_image_url: '$type_detail.type_image_url',
                service_name:"$vehicle_detail.service_name",
                pictureData:"$vehicle_detail.pictureData"
            }}
    }
}
Provider.aggregate([condition, vunwind, lookup, unwind, group], function (err, provider) {

    if (err || provider.length == 0) {
        res.json({success: true, vehicle_list: []})
    } else {
        res.json({success: true, vehicle_list: provider[0].vehicle_detail})
    }

})
* *} 1 022;

, а мой res как ниже:

{
"success": true,
"vehicle_list": [
    {
        "is_selected": true,
        "admin_type_id": "5a9f9b55b9e8fa66f9b934c0",
        "service_type": [
            "5a9f9c53b9e8fa66f9b934c1",
            "5ac954b7075e16583dc3311f"
        ],
        "passing_year": "2005",
        "color": "Blue",
        "model": "Qee",
        "plate_no": "Qwe111",
        "name": "Qee",
        "_id": "5aec2d08020ba15d2fb2665c",
        "type_image_url": "service_type_images/5a9f9b55b9e8fa66f9b934c0mjYA.png",
        "service_name": "You",
        "pictureData": "vehicle_images/5aec2d08020ba15d2fb2665cWjyP.jpg"
    }
]

}

и разрешение, которое я хочу, ниже

{
"success": true,
"vehicle_list": [
    {
        "is_selected": true,
        "admin_type_id": "5a9f9b55b9e8fa66f9b934c0",
        "service_type": [
            "5a9f9c53b9e8fa66f9b934c1",
            "5ac954b7075e16583dc3311f"
        ],
        "passing_year": "2005",
        "color": "Blue",
        "model": "Qee",
        "plate_no": "Qwe111",
        "name": "Qee",
        "_id": "5aec2d08020ba15d2fb2665c",
        "type_image_url": "service_type_images/5a9f9b55b9e8fa66f9b934c0mjYA.png",
        "service_type_name": [
            "You"
        ],
        "service_name": "You",
        "pictureData": "vehicle_images/5aec2d08020ba15d2fb2665cWjyP.jpg"
    }
]

}

Ответы [ 2 ]

0 голосов
/ 05 мая 2018

пожалуйста, проверьте.

db.getCollection('vehicle').aggregate([
  {
      $unwind: {
        path: '$vehicle_detail',
        preserveNullAndEmptyArrays: true,
      },
    },
    {
      $unwind: {
        path: '$vehicle_detail.service_type',
        preserveNullAndEmptyArrays: true,
      },
    },
     {
      $lookup: {
        from: 'city_type',
        localField: 'vehicle_detail.service_type',
        foreignField: '_id',
        as: 'city_type',
      },
    },
    {
      $unwind: {
        path: '$city_type',
        preserveNullAndEmptyArrays: true,
      },
    },
      {
      $lookup: {
        from: 'types',
        localField: 'city_type.typeid',
        foreignField: '_id',
        as: 'types',
      },
    },
    {
      $unwind: {
        path: '$types',
        preserveNullAndEmptyArrays: false,
      },
    },
    {
        $group: {
          _id: '$_id',
          first_name: { $first: 1 }, 
          last_name: { $first: 1 }, 
          types: { $first: '$types' },
        },
      },
])

Результат

{
    "_id" : ObjectId("5aec2ce5020ba15d2fb2665a"),
    "first_name" : 1.0,
    "last_name" : 1.0,
    "types" : {
        "_id" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
        "typename" : "You",
        "description" : "KARRU You",
        "__v" : 0,
        "main_type" : 0
    }
}

Примечание : Вы можете добавить поля в нужную группу.

0 голосов
/ 04 мая 2018

Я отправляю то, что понял из вашего объяснения. Надеюсь, это поможет.

Некоторые баллы:

  1. Я изменил ваши объекты city_types и типы на массив, так как вы сказали Коллекции;
  2. Я связываю идентификатор для соответствия Автомобиль-> Город-> Типы

            function ObjectId(id){
                return id;
            }
    
            var obj = {"_id" : ObjectId("5aec2ce5020ba15d2fb2665a"),
                "password" : "e10adc3949ba59abbe56e057f20f883e",
                "unique_id" : 22,
                "first_name" : "Foram",
                "last_name" : "Test ",
                "country_phone_code" : "+61",
                "email" : "a@a.com",
                "phone" : "1231231231",
                "device_type" : "android",
                "admintypeid" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
                "vehicle_detail" : [ 
                {
                    "service_name" : "Service 1",
                    "_id" : ObjectId("5aec2d08020ba15d2fb2665c"),
                    "name" : "Qee",
                    "plate_no" : "Qwe111",
                    "model" : "Qee",
                    "color" : "Blue",
                    "passing_year" : "2005",
                    "service_type" : [ 
                        ObjectId("5a9f9c53b9e8fa66f9b934c1")
                    ],
                    "admin_type_id" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
                    "is_selected" : true,
                    "pictureData" : "vehicle_images/5aec2d08020ba15d2fb2665cWjyP.jpg"
                }, 
                {
                    "pictureData" : "vehicle_images/5aec35e00efc106080e14ec7y2tO.jpg",
                    "is_selected" : false,
                    "admin_type_id" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
                    "service_type" : [ 
                        ObjectId("5a9f9c53b9e8fa66f9b934c1"), 
                        ObjectId("5ac954b7075e16583dc3311f")
                    ],
                    "passing_year" : "2018",
                    "color" : "No",
                    "model" : "Bcs",
                    "plate_no" : "12112",
                    "name" : "Bcs",
                    "_id" : ObjectId("5aec35e00efc106080e14ec7"),
                    "service_name" : "Service 2"
                }
            ],
            "service_type" : [ 
                ObjectId("5a9f9c53b9e8fa66f9b934c1")
            ],
            "is_vehicle_document_uploaded" : true,
            "is_trip" : [],
            "__v" : 14
            };
    
            var city_types = [{
                "_id" : ObjectId("5aec2d08020ba15d2fb2665c"),
                "countryid" : ObjectId("5abb275fd20731597cc01229"),
                "cityid" : ObjectId("5abb27cbd20731597cc0122a"),
                "typeid" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
                "__v" : 0
            }];
    
            var types = [{
                "_id" : ObjectId("5a9f9b55b9e8fa66f9b934c0"),
                "typename" : "You",
                "description" : "KARRU You",
                "__v" : 0,
                "main_type" : 0
            }];
    
            function print() {
                    //iterate over vehicle_detail
                    obj.vehicle_detail.forEach((vehicle)=>{
                        console.log("vehicle="+ vehicle._id);
                        //iterate over cities type
                        city_types.forEach((city)=> {
                            console.log("city="+ city._id);
                            if (city._id == vehicle._id) {
                                //iterate over types
                                types.forEach((type)=> {
                                    console.log("type="+ type._id);
                                    if (city.typeid == type._id) {
                                       console.log("Type Name: "+type.typename);
                                    }
                                })
                            }
                        })
                    });
    
            }
    
            print();
    

Вывод программы:

>node index4.js
vehicle=5aec2d08020ba15d2fb2665c
city=5aec2d08020ba15d2fb2665c
type=5a9f9b55b9e8fa66f9b934c0
Type Name: You
vehicle=5aec35e00efc106080e14ec7
city=5aec2d08020ba15d2fb2665c
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...