Extract keys from a collection and insert in to another collection mongodb

Viewed 24
event_time event_type category_code
2019-10-01 00:00:00 UTC view appliances.environment.water_heater
2019-10-01 00:00:00 UTC cart furniture.living_room.sofa

Above is the CSV file I have imported into the MongoDb. Now I want to extract certain columns(event time and event type) from the existing collection into a new collection, without reimporting them again using CSV file. Is there any query to do it? All I have found on Google is just the copy method, which cannot be used as I only need some of the columns.

1 Answers

Easiest way is to use the $out stage, it exports the current pipeline results into the specified collection, like so:

db.collection.aggregate([
    {
        $project: {
            _id: 0,
            event_type: 1,
            event_type: 1,
            // any other structure manipulation we want
        }
    },
    {
        $out: "new-collection-name" // this will repalce this collection if exists!
    }
])
Related