sgp
sgp

Reputation: 87

How to split a mongodb collection into multiple collection based on a field

I have a single collection in mongo, and I would like to split that collection to multiple collections based on the key/field "source". The "source" value should be the new collection name with documents that are of that source.

{
"name": "Name"
"ph": {"phone": "1111"}
"source": "source1"
},
{
"name": "Name Last"
"ph": {"phone": "2121"}
"source": "source2"
}

How can I achieve this at mongodb itself? Thanks in advance

Upvotes: 0

Views: 1740

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

You can run the below script on Mongo Shell to achieve it.

var collectionName = "<CollectionName>"
var distinctValues = db.getCollection(collectionName).distinct("source")
var count = 0;
for (var i = 0; i < distinctValues.length; i++) {
    var newCollectionName = collectionName.concat("_".concat(distinctValues[i]))
    db.getCollection(collectionName).aggregate([
        {
            "$match": {
                "source": distinctValues[i]
            }
        },
        {
            "$out": newCollectionName
        }
    ], {
        allowDiskUse: true
    });
    printjson(++count);
}
printjson("DONE!!!")

Upvotes: 1

Related Questions