Как найти и вернуть поле и данные в многоуровневом массиве объектов? - PullRequest
0 голосов
/ 23 октября 2019

У меня есть набор данных, возвращенный командой find в MongoDB. Как найти значение и поле DeviceJson [] в заданных данных


{ location: [],
  _id: 5d42d171e7ceef2a90245470,
  farmName: 'Xilo',
  description: 'This is test from Postman Api Request',
  farmAddDate: 2019-08-01T11:48:01.883Z,
  device:
   [ 
     { _id: 5d441878f1877637cc712d07,
       deviceName: 'Xki',
       deviceType: 'Muc',
       description:
        'This is test for updation of specific data in a specfic farm .Test Pass',
       deviceLocation: [Array],
       Parameter: 'Hello Happy',
       Topic: 'v1/Xki/11,180/Hello Happy' },
     { _id: 5d4418953968370e64c32e1f,
       deviceName: 'Xki',
       deviceType: 'Muc',
       description:
        'This is test for updation of specific data in a specfic farm .Test Pass',
       deviceLocation: [Array],
       Parameter: 'Hello Happy',
       Topic: 'v1/Xki/11,180/Hello Happy' },
     { _id: 5d4425548b3cf92af46e2c9a,
       deviceName: 'Xki',
       deviceType: 'Muc',
       description:
        'This is test for updation of specific data in a specfic farm .Test Pass',
       deviceLocation: [Array],
       Parameter: 'Hello Happy 1',
       Topic: 'sagita/5d42d171e7ceef2a90245470/Xki/11,180/Hello Happy 1' },
     { _id: 5d44256d8b3cf92af46e2c9b,
       deviceName: ' DeviceX01',
       deviceType: ' Test',
       description: ' This is a test',
       deviceLocation: '11.22,33.12',
       Parameter: ' set',
       Topic:
        'sagita/5d42d171e7ceef2a90245470/ DeviceX01/11.22,33.12/ set',
       DeviceJson: [Array] } 
    ] 
  }


Набор данных, который я сохранил в массиве с именем usdData = [] и просматривал его индекс иэто результат, и я хочу найти даже Интерьер и значение DeviceJson в схеме. Как я могу это сделать?

var usdData=[];


      collection.findOne({"email":Username},function (err,doc) {
        if (err) throw err;
         usdData=doc.farm;

           for (let index = 0; index < usdData.length; index++) {

            if (usdData[index].farmName === gotfarmName) {

               return  usdData[index];
            }
             const element = usdData[index];

                 //  const dElement = JSON.stringify(element);
                //   console.log("Array started here \n"+dElement); 
                //   const ddElement= JSON.parse(dElement) ;
                console.log(usdData[1]);


           }

          return console.log();
          });

1 Ответ

0 голосов
/ 29 октября 2019

Если вам известна структура «DeviceJson», вы можете сделать что-то вроде этого:

01) Пример документа:

{
    "_id" : "5d42d171e7ceef2a90245470",
    "location" : [],
    "farmName" : "Xilo",
    "description" : "This is test from Postman Api Request",
    "farmAddDate" : "2019-08-01T11:48:01.883Z",
    "device" : [ 
        {
            "_id" : "5d441878f1877637cc712d07",
            "deviceName" : "Xki",
            "deviceType" : "Muc",
            "description" : "This is test for updation of specific data in a specfic farm .Test Pass",
            "deviceLocation" : [],
            "Parameter" : "Hello Happy",
            "Topic" : "v1/Xki/11,180/Hello Happy"
        }, 
        {
            "_id" : "5d4418953968370e64c32e1f",
            "deviceName" : "Xki",
            "deviceType" : "Muc",
            "description" : "This is test for updation of specific data in a specfic farm .Test Pass",
            "deviceLocation" : [],
            "Parameter" : "Hello Happy",
            "Topic" : "v1/Xki/11,180/Hello Happy"
        }, 
        {
            "_id" : "5d4425548b3cf92af46e2c9a",
            "deviceName" : "Xki",
            "deviceType" : "Muc",
            "description" : "This is test for updation of specific data in a specfic farm .Test Pass",
            "deviceLocation" : [],
            "Parameter" : "Hello Happy 1",
            "Topic" : "sagita/5d42d171e7ceef2a90245470/Xki/11,180/Hello Happy 1"
        }, 
        {
            "_id" : "5d44256d8b3cf92af46e2c9b",
            "deviceName" : "DeviceX01",
            "deviceType" : " Test",
            "description" : " This is a test",
            "deviceLocation" : "11.22,33.12",
            "Parameter" : " set",
            "Topic" : "sagita/5d42d171e7ceef2a90245470/ DeviceX01/11.22,33.12/ set",
            "DeviceJson" : [ 
                {
                    "_id" : "5db85e439a17899b8ba631cd",
                    "name" : "deviceJsonOne",
                    "complexObject" : {
                        "_id" : "5db85e439a17899b8ba631ce"
                    },
                    "someArray" : [ 
                        {
                            "someThing" : 1
                        }, 
                        {
                            "someThing" : 2
                        }
                    ]
                }, 
                {
                    "_id" : "5dae22702486f7d89ba7633c",
                    "name" : "deviceJsonTwo",
                    "complexObject" : {
                        "_id" : "5db85e439a17899b8ba631cf"
                    },
                    "someArray" : [ 
                        {
                            "someThing" : 3
                        }, 
                        {
                            "someThing" : 2
                        }
                    ]
                }
            ]
        }
    ]
}

02) Запрос:

    db.Collection.aggregate([
    // INITIAL FILTER... HERE YOU CAN FILTER FOR ANY FILTERS...
    { 
        $match: { "device._id" : "5d44256d8b3cf92af46e2c9b"}
    },
    // TRANSFORMING EVERY ELEMENT OF THE ARRAY 'device' AS A SINGLE ROW/DOCUMENT...
    // EXAMPLE: 
    // {id: 123, "someArray":["A","B","C"]} 
    //          --> unwind : 'someArray' 
    //          --> [{"id": 123, "someArray": "A"},{"id": 123, "someArray": "B"},{"id": 123, "someArray": "C"}]
    {
        $unwind: '$device'
    },
    // FILTERING THE DEVICES THAT HAVE THE 'DeviceJson' PROPOERTY...
    { 
        $match: { "device.DeviceJson" : {$exists: true}}
    },
    // TRANSFORMING EVERY ELEMENT OF THE ARRAY 'DeviceJson' AS A SINGLE ROW/DOCUMENT...
    {
        $unwind: '$device.DeviceJson'
    },
    // FILTERING THE ELEMENTS IN "DeviceJson"...
    { 
        $match: { "device.DeviceJson.complexObject._id" : "5db85e439a17899b8ba631cf"}
    },
    // CREATING A FIELD TO STORE THE RESULT...
    {
        $addFields: {"DeviceJson" : "$device.DeviceJson" }
    },
    // SHOWING ONLY THE FIELD 'DeviceJson' IN THE RESULT...
    {
        $project: {"DeviceJson" : 1}
    }
]);

03) Ответ:

{
    "_id" : "5d42d171e7ceef2a90245470",
    "DeviceJson" : {
        "_id" : "5dae22702486f7d89ba7633c",
        "name" : "deviceJsonTwo",
        "complexObject" : {
            "_id" : "5db85e439a17899b8ba631cf"
        },
        "someArray" : [ 
            {
                "someThing" : 3
            }, 
            {
                "someThing" : 2
            }
        ]
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...