Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: export distinct column value

Anyone have idea how to export distinct column value on mongodb using mongoexport command.

Command: db.coll.distinct("uid");

The solution i have tried is :

 mongoexport --csv -d db -c collection -q '{distinct: "collection", "key": "uid"}' -f "uid" -o distinctUid.csv
like image 723
Yogesh Prajapati Avatar asked Oct 04 '17 08:10

Yogesh Prajapati


2 Answers

It's not possible to do it this way. distinct is a database command, and --query option allows to use only a query to filter documents.

If you are using mongodb v3.4 or later, you can use views to aggregate your collection and export it from the view.

First create the view in mongo shell:

db.createView("distinctCollectionUid", "collection", [{ $group: { _id: "$uid"}}]);

Then export it:

mongoexport -d db -c distinctCollectionUid --type=csv -f "_id" -o distinctUid.csv
like image 105
Alex Blex Avatar answered Oct 03 '22 09:10

Alex Blex


its working for me.

Example:

First create view:

db.createView("distinctCollectionBI2_Style( BI2_Style is  key which value must distinc)","best_seller_data(your collection name)", [{ $group: { _id: "$BI2_Style"}}]);

Then export:

mongoexport -d best-seller(db name) -c distinctCollectionBI2_Style --type=csv -f "_id" -o Desktop/pretr/style.csv
like image 42
Manoj kumar Yadav Avatar answered Oct 03 '22 09:10

Manoj kumar Yadav