How to delete a document from collection using Mongodb Aggregation?

Refresh

November 2018

Views

116 time

4

I have two collections. Locations and Archiveloc. I would like to enter particular document to archiveloc from locations after passing some conditions. And then, that particular document is needed to be deleted from the Locations collection after transferring it to Archiveloc. I could transfer documents to Archiveloc but cannot delete that from Locations collection. Below is my code

locations.aggregate([
        {
            $sort: {
                createdAt: -1
            }
                },
        {
            $group: {

                _id: '$imei',
                total_imei: {
                    $sum: 1,


                },

                "firstDoc": {
                    "$first": "$_id",

                },
                object: {
                    $push: "$$ROOT",


                },


            }
                },



        {
            $match: {

                total_imei: {
                    $gt: 2
                }
            }
                },

        {
            $out: "archiveloc",

                        }



    ].exec(function (e, d) {
        console.log(d);
        d.forEach(function (data) {

            console.log(data);
            // return temp;
            // console.log(temp);


        });

    }));

Quick help will be much appreciated. Thanks in advance.

For test purpose, example of documents is provided below:

For the collection called Locations:

{
"_id" : ObjectId("57010cde76fe39110d716ad0"),
"sourcedevice" : "tcpping",
"imei" : "86669902366722",
"commandtype" : "AAA",
"latitude" : "0.41995433112606406",
"longitude" : "0.43301976611837745",
"datetime" : ISODate("2016-04-03T12:30:22.401Z"),
"status" : "A",
"mileage" : "10418109",
"run_time" : "12854934",
"base_station_info" : "470|1|61E0|43C4",
"io_port_status" : "0000",
"analog_input" : "0000|0000|0000|02D3|010A",
"increment_index" : 1459686622401.0000000000000000,
"__v" : 0}

Documents for Archiveloc collection:

{
"_id" : "86669902366722",
"total_imei" : 45,
"firstDoc" : ObjectId("57010cde76fe39110d716ad0"),
"object" : [ 
    {
        "_id" : ObjectId("57010cde76fe39110d716ad0"),
        "sourcedevice" : "tcpping",
        "imei" : "86669902366722",
        "commandtype" : "AAA",
        "latitude" : "0.41995433112606406",
        "longitude" : "0.43301976611837745",
        "direction" : "83",
        "horizaontal_accuracy" : "0.8",
        "altitude" : "6",
        "mileage" : "10418109",
        "run_time" : "12854934",
        "base_station_info" : "470|1|61E0|43C4",
        "io_port_status" : "0000",
        "analog_input" : "0000|0000|0000|02D3|010A",
        "increment_index" : 1459686622401.0000000000000000,
        "__v" : 0
    }
]}

0 answers