0

I want to export a single field from a single collection. Like collection name is products and field name is tag.
All tag will create new collection. I have tried this command:

mongodump --host 192.168.1.46 --port 27017 --db myDb --collection products --fields tag -o bson  --out C:\Users\Desktop\tag
TGrif
  • 5,725
  • 9
  • 31
  • 52
  • Have you got an example of your documents in that `products` collection? – Kevin Smith Dec 17 '16 at 15:42
  • Can you clarify what `All tag will create new collection.` means? Do you just want to get find all the tags and create a new collection in the same database? – Kevin Smith Dec 17 '16 at 16:52
  • Hello Kevin, i just wanted to export a single filed from a collection and wanted to create a new collection from those exported field. eg(if products collection has tags field which is string and i just wanted to export all the tags from the products collection and after that exported tags will create a new collection like Tag) hope now you are bettor understand. – Omprakash Amarwal Jan 02 '17 at 05:31
  • See my answer, should fit that criteria – Kevin Smith Jan 04 '17 at 12:58

2 Answers2

1

mongodump doesn't support the selected field's backup. But you can use mongoexport/mongoimport to backup selected fields as:

mongoexport -c test --db testing -f key --out dump.json
Sourbh Gupta
  • 808
  • 7
  • 16
1

So lets start by inserting some products in to our collection:

db.products.insertMany([
    { name: 'TV', tags: ['livingroom', 'electronics']},
    { name: 'Radio', tags: ['bedroom', 'electronics']},
    { name: 'Computer', tags: ['bedroom', 'electronics']}
]);

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("586bae0ec5a9a94b2674943d"),
                ObjectId("586bae0ec5a9a94b2674943e"),
                ObjectId("586bae0ec5a9a94b2674943f")
        ]
}

We can now write a simple aggreation query to go though all the documents

db.products.aggregate([
    {$unwind: '$tags'},
    {$group: {_id: '$tags' }},
    {$out: 'productTags'}
]);

The {$unwind: '$tags'} will deconstruct the tags array field in to a document for each tag. Then the {$group: {_id: '$tags' }} will group each item and create a new document for each tag. Then the {$out: 'productTags'} will create us a productTags collection with the output of the documents.

now if we query the productTags collection we'll get the following output:

> db.productTags.find()
{ "_id" : "bedroom" }
{ "_id" : "electronics" }
{ "_id" : "livingroom" }
Kevin Smith
  • 13,746
  • 4
  • 52
  • 77